javafx webview加载本地css文件

Get*_*awn 3 html css java javafx webview

我有一个WebView,它加载我在项目中保存的本地 html 文件。我使用以下命令来加载文件:

InputStream is = Browser.class.getResourceAsStream(location);
String str = "";
int i;
while((i = is.read()) != -1){
    str += (char)i;
}

str = str.replace("{placeholder_1}", value1);
str = str.replace("{placeholder_2}", value2);


webEngine.loadContent(str);
Run Code Online (Sandbox Code Playgroud)

在 HTML 中,我有一个 css 文件的链接。HTML 文件和 css 文件位于同一目录中,但在 .css 文件中加载页面时,不会加载 css 文件WebView。以下是我从 HTML 调用 css 文件的方法:

<link rel="stylesheet" href="main.css" />
Run Code Online (Sandbox Code Playgroud)

为什么文件无法加载?据其他人说,他们就是这样做的,而且正在发挥作用。为什么它对我不起作用,我做错了什么?

这是目录布局:

目录列表

Ulu*_*Biy 5

将 css 文件与 html 文件放在同一目录中,如果

webView.getEngine().load(location);
Run Code Online (Sandbox Code Playgroud)

用来。但是,它不适用于loadContent(). 您需要将 css 文件位置显式定义为:

(伪代码)

str = str.replace("href='main.css'", 
                  "href='" + getClass().getResource("main.css") + "'");
Run Code Online (Sandbox Code Playgroud)

  • [我刚刚发现](http://stackoverflow.com/questions/20164062/how-to-load-both-html-and-javascript-into-webengine-from-loadcontent/26488496#26488496)使用`&lt; base&gt;` 标签是使用 loadContent(String)` 加载相关资源的技巧。我搜索了很长时间才找到这样的解决方案,所以我想分享它。:) (2认同)