好吧,我有一个 html 文件,其标签指向文件夹/img/中的图像。通过 JavaFX 窗口应用程序(不在 html 文件的同一路径中),我加载了 html 文件,但没有加载图像。 这是我加载 html 文件的方式:
@FXML
WebView webView; // I get the webView through @FXML annotation
...
webView.getEngine().loadContent("path/to/file.html");
HTML 文件结构:
path/to/file.html
path/to/img/image.png
这是 HTML 内容:
<h1 style="color:red; font-style: italic">
This is opencraft's presentation :)
</h1>
<img src="img/image.png">
<p>
This is a simple description of how the game works, lol.
</p>
如果我用浏览器加载图像,图像会被加载
谁能帮帮我?
最佳答案
基本上,问题是您需要一个完整的 URL,包括方案等,以便 html 中的相关链接起作用。与当前类或工作目录相关的 URL 将不起作用。
假设 html 文件和关联的图像与应用程序捆绑在一起(即,当您为应用程序构建 jar 文件时,html 文件和图像将成为 jar 文件的一部分),那么您可以检索 URL带有
的html文件getClass().getClassLoader().getResource("path/to/file.html");
路径是相对于类路径的。然后,您可以使用 toExternalForm()
以适当的格式转换为 String
。这适用于 html 帮助页面等。
这是一个例子:
HTMLTest.java:
package htmltest;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class HTMLTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
WebView webView = new WebView();
webView.getEngine().load(getClass().getClassLoader().getResource("htmltest/html/test.html").toExternalForm());
Scene scene = new Scene(webView, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
测试.html:
<html>
<head><title>Test</title></head>
<body>
<h1>Test page</h1>
<img src="img/testImage.png"/>
</body>
</html>
测试图像.png:
项目布局:
htmltest
- HTMLTest.class
- html
- test.html
- img
- testImage.png
截图:
另一方面,如果您真正从文件系统加载 HTML 文件,您可以为 HTML 文件创建一个 File
对象,然后将其转换为 URI。这将是合适的,例如,如果您正在编写一个 HTML 编辑器,用户在其中编辑 HTML 文件并将其保存到文件系统,并且您希望在 Web View 中显示结果;或者,如果您提示用户使用 FileChooser
加载 HTML 文件。
代码如下:
File htmlFile = new File(...); // or get from filechooser...
webEngine.load(htmlFile.toURI().toString());
关于JavaFX WebView html加载器不加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400222/