好吧,我有一个带有标签的html文件,指向文件夹/ img /中的图像.通过JavaFX窗口应用程序(不在html文件的相同路径中)我加载html文件,但图像不加载.这是我加载html文件的方式:
@FXML
WebView webView; // I get the webView through @FXML annotation
...
webView.getEngine().loadContent("path/to/file.html");
Run Code Online (Sandbox Code Playgroud)
HTML文件结构:
path/to/file.html
path/to/img/image.png
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
如果我用浏览器加载它,图像就会加载
有人可以帮帮我吗?
基本上,问题是您需要一个完整的 URL(包括方案等)才能使 html 中的相关链接正常工作。相对于当前类或工作目录的 URL 将不起作用。
假设 html 文件和关联的图像与应用程序捆绑在一起(即,当您为应用程序构建 jar 文件时,html 文件和图像将成为 jar 文件的一部分),那么您可以使用以下命令检索 html 文件的 URL
getClass().getClassLoader().getResource("path/to/file.html");
Run Code Online (Sandbox Code Playgroud)
其中路径是相对于类路径的。然后您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
测试.html:
getClass().getClassLoader().getResource("path/to/file.html");
Run Code Online (Sandbox Code Playgroud)
测试图像.png:
项目布局:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
截屏:
另一方面,如果您真正从文件系统加载 HTML 文件,则可File以为 HTML 文件创建一个对象,然后将其转换为 URI。例如,如果您正在编写一个 HTML 编辑器,用户在其中编辑 HTML 文件并将其保存到文件系统,并且您希望在 Web 视图中显示结果,那么这将是合适的;或者,如果您提示用户加载扩展名为FileChooser.
其代码如下所示:
File htmlFile = new File(...); // or get from filechooser...
webEngine.load(htmlFile.toURI().toString());
Run Code Online (Sandbox Code Playgroud)