[英]How to load local html file in java swing?
我有一個樹列表,當我單擊一個節點時,它將打開一個特定的 html 文件。 我嘗試將我的 html 加載到 Jeditorpanel 中,但它似乎無法正常工作。
這是我的主文件中的代碼:
private void treeItemMouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) treeItem.getSelectionPath().getLastPathComponent();
String checkLeaf = selectedNode.getUserObject().toString();
if (checkLeaf == "Java Turtorial 1") {
String htmlURL = "/htmlFILE/javaTurtorial1.html";
new displayHTML(htmlURL).setVisible(true);
}
}
我想在哪里顯示它:
public displayHTML(String htmlURL) {
initComponents();
try {
//Display html file
editorHTML.setPage(htmlURL);
} catch (IOException ex) {
Logger.getLogger(displayHTML.class.getName()).log(Level.SEVERE, null, ex);
}
}
我的文件:
使用 JEditorPane 呈現 HTML 的一種簡單方法是使用它的setText
方法:
JEditorPane editorPane =...
editorPane.setContentType( "text/html" );
editorPane.setText( "<html><body><h1>I'm an html to render</h1></body></html>" );
請注意,只有某些 HTML 頁面(相對簡單的頁面)可以使用此 JEditoPane 呈現,如果您需要更復雜的內容,則必須使用第三方組件
根據 OP 的評論,我正在為答案添加更新:
更新
由於您嘗試加載的 HTML 是 JAR 中的文件,因此您應該將文件讀入某個字符串變量並使用上述方法setText
請注意,您不應使用java.io.File
,因為它用於識別文件系統中的資源,並且您正在嘗試訪問工件內部的某些內容:
像這樣讀取資源可以通過以下結構來完成:
InputStream is = getClass().getResourceAsStream("/htmls/myhtml.html");
// and then read with the help of variety of ways, depending on Java Version of your choice and by the availaility by auxiliary thirdparties
// here is the most simple way IMO for Java 9+
String htmlString = new String(input.readAllBytes(), StandardCharsets.UTF_8);
在此處閱讀有關將 InputStream 讀入 String 的許多不同方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.