2014-05-15 107 views
1

我有一個WebView,它加載了我保存在我的項目中的本地html文件。我使用以下來加載文件:javafx webview加載本地css文件

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

把在同一目錄中的HTML文件CSS文件,將工作,如果

webView.getEngine().load(location); 
使用

。但是它不適用於loadContent()。你需要明確定義的CSS文件的位置爲:

(僞代碼)

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

[我剛剛發現](http://stackoverflow.com/questions/20164062/how-to-load-both-html-and-javascript -into-webengine-from-loadcontent/26488496#26488496)使用''標籤是利用'loadContent(String)'加載相關資源的技巧。我搜索了很長時間,所以我想分享它。 :) – Huxi

1

如下的東西爲我工作

項目結構

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

WebViewLoadLocalFile

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; 
} 
+0

我在HTML佔位符,我用之前,我在頁面上顯示的實際HTML取代。直接加載文件不起作用。我已經更新了這個問題。 –

+0

一些代碼會非常有幫助! – ItachiUchiha

+0

對我來說,當我在eclipse中運行上面的代碼時,我可以加載html文件中指定的css。但是,當我將它編譯爲jar文件並運行它時,它不起作用。我認爲它與查找jar文件內的css文件路徑的問題有關。 – mk7

相關問題