JavaFX WebView 加载本地 CSS 文件

3

我有一个 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);

在HTML中,我有一个指向CSS文件的链接。HTML文件和CSS文件在同一个目录下,但是当页面在WebView中加载时,CSS文件没有加载。以下是我如何从HTML中调用CSS文件的方式:
<link rel="stylesheet" href="main.css" />

为什么文件无法加载?根据其他人的说法,这是他们的做法,并且有效。为什么对我无效,我做错了什么?

这是目录布局:

Directory Listing

2个回答

5
将CSS文件放在与HTML文件相同的目录中,如果以下条件成立,则可以正常工作:
webView.getEngine().load(location);

该方法被使用。但是对于loadContent(),它将不起作用。您需要显式地定义CSS文件位置,例如:

(伪代码)

str = str.replace("href='main.css'", 
                  "href='" + getClass().getResource("main.css") + "'");

2
我刚刚发现使用<base>标签是在使用loadContent(String)加载相对资源的技巧。我为此搜索了很长时间,所以我想分享一下。 :) - Huxi

1

以下东西对我有效

项目结构

Application
|
 src
    |
    package
           |
           WebViewLoadLocalFile.java
           test.html
           test.css

WebView加载本地文件

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class WebViewLoadLocalFile extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        BorderPane borderPane = new BorderPane();
        WebView webView = new WebView();
        String url = getClass().getResource("test.html").toExternalForm();
        webView.getEngine().load(url);
        borderPane.setCenter(webView);
        final Scene scene = new Scene(borderPane);
        stage.setScene(scene);
        stage.setHeight(300);
        stage.setWidth(250);
        stage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

test.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
Test HTML
</body>
</html>

test.css

body
{
  background-color:#d0e4fe;
}

在HTML中我有占位符,我会在显示实际HTML之前用其他内容替换它们。直接加载文件是行不通的。我已经更新了问题。 - Get Off My Lawn
对我来说,当我在Eclipse中运行上述代码时,我可以加载HTML文件中指定的CSS。然而,当我将其编译为JAR文件并运行它时,它不起作用。我认为这与在JAR文件中找到CSS文件路径的问题有关。 - mk7
@mk7 将资源复制到您的jar包取决于您的项目配置。我认为创建一个带有必要数据的新问题将会非常有帮助。 - ItachiUchiha
真棒。它起作用了。String url = getClass().getResource("test.html").toExternalForm(); webView.getEngine().load(url); 这就是解决问题的办法。 - Vishrant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接