gpt4 book ai didi

JavaFX 资源处理 : Load HTML files in WebView

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:36:44 24 4
gpt4 key购买 nike

我想在我的 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() 有多种选择:

如果资源和类在同一个目录,那么你可以使用

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();

是等价的。

要进一步阅读,您可以查看 the documentation of getResource() .

关于JavaFX 资源处理 : Load HTML files in WebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37359583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com