JavaFX 资源处理:在 WebView 中加载 HTML 个文件
JavaFX resource handling: Load HTML files in WebView
我想在我的 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();
}
但是它抛出一个异常说:
Exception in Application start method
java.lang.reflect.InvocationTargetException
你得到这个异常是因为你的 url
变量在这行是空的:
String url = WebViewSample.class.getResource("/map.html").toExternalForm();
getResource()
你有几个选项:
如果资源与class在同一个目录,那么您可以使用
String url = WebViewSample.class.getResource("map.html").toExternalForm();
使用开头的斜线("/")表示项目根目录的相对路径。:
在您的特定情况下,如果资源存储在 webviewsample
包中,您可以获得资源:
String url = WebViewSample.class.getResource("/webviewsample/map.html").toExternalForm();
使用 开头的点斜杠 ("./") 表示 class:
的相对路径
假设您的 rclass 存储在包 webviewsample
中,您的资源 (map.html
) 存储在子目录 res
中。您可以使用此命令获取 URL:
String url = WebViewSample.class.getResource("./res/map.html").toExternalForm();
据此,如果你的资源和你的class在同一个目录下,那么:
String url = WebViewSample.class.getResource("map.html").toExternalForm();
和
String url = WebViewSample.class.getResource("./map.html").toExternalForm();
是等价的。
如需进一步阅读,您可以查看 the documentation of getResource()
。
我想在我的 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();
}
但是它抛出一个异常说:
Exception in Application start method java.lang.reflect.InvocationTargetException
你得到这个异常是因为你的 url
变量在这行是空的:
String url = WebViewSample.class.getResource("/map.html").toExternalForm();
getResource()
你有几个选项:
如果资源与class在同一个目录,那么您可以使用
String url = WebViewSample.class.getResource("map.html").toExternalForm();
使用开头的斜线("/")表示项目根目录的相对路径。:
在您的特定情况下,如果资源存储在 webviewsample
包中,您可以获得资源:
String url = WebViewSample.class.getResource("/webviewsample/map.html").toExternalForm();
使用 开头的点斜杠 ("./") 表示 class:
的相对路径假设您的 rclass 存储在包 webviewsample
中,您的资源 (map.html
) 存储在子目录 res
中。您可以使用此命令获取 URL:
String url = WebViewSample.class.getResource("./res/map.html").toExternalForm();
据此,如果你的资源和你的class在同一个目录下,那么:
String url = WebViewSample.class.getResource("map.html").toExternalForm();
和
String url = WebViewSample.class.getResource("./map.html").toExternalForm();
是等价的。
如需进一步阅读,您可以查看 the documentation of getResource()
。