JavaFX资源处理:在WebView中加载HTML文件
我想在我的JavaFX应用程序的WebView
中加载HTML文件。 该文件位于我的项目目录中,位于webviewsample
包中。
我使用了以下代码:
public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("WebView test"); WebView browser = new WebView(); WebEngine engine = browser.getEngine(); String url = WebViewSample.class.getResource("/map.html").toExternalForm(); engine.load(url); StackPane sp = new StackPane(); sp.getChildren().add(browser); Scene root = new Scene(sp); primaryStage.setScene(root); primaryStage.show(); }
但它抛出一个例外说:
Application start方法java.lang.reflect.InvocationTargetException中的exception
您得到此exception,因为此行上的url
变量为null:
String url = WebViewSample.class.getResource("/map.html").toExternalForm();
getResource()
有几个选项:
如果资源与类相同 ,则可以使用
String url = WebViewSample.class.getResource("map.html").toExternalForm();
使用开始斜杠(“/”)表示项目根目录的相对路径。 :
在您的特定情况下,如果资源存储在webviewsample
包中,您可以获取资源:
String url = WebViewSample.class.getResource("/webviewsample/map.html").toExternalForm();
使用起始点斜杠(“./”)表示类路径的相对路径 :
想象一下,你的rclass存储在webviewsample
包中,你的资源( map.html
)存储在子目录res
。 您可以使用此命令获取URL:
String url = WebViewSample.class.getResource("./res/map.html").toExternalForm();
基于此,如果您的资源与您的类在同一目录中,则:
String url = WebViewSample.class.getResource("map.html").toExternalForm();
和
String url = WebViewSample.class.getResource("./map.html").toExternalForm();
是等价的。
有关进一步阅读,您可以查看getResource()
的文档 。