简体   繁体   English

如何在java swing中加载本地html文件?

[英]How to load local html file in java swing?

I have a tree list which will open a specific html file when I click at a node.我有一个树列表,当我单击一个节点时,它将打开一个特定的 html 文件。 I try loading my html into a Jeditorpanel but it can't seem to work.我尝试将我的 html 加载到 Jeditorpanel 中,但它似乎无法正常工作。

Here's my code from main file:这是我的主文件中的代码:

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);
    }
}

Where I wanna display it:我想在哪里显示它:

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);
    }
}

My files:我的文件:

在此处输入图像描述

One simple way to render HTML with JEditorPane is using it's setText method:使用 JEditorPane 呈现 HTML 的一种简单方法是使用它的setText方法:

JEditorPane editorPane =...

editorPane.setContentType( "text/html" );    
editorPane.setText( "<html><body><h1>I'm an html to render</h1></body></html>" );

Note that only certain HTML pages (relatively simple ones) can be rendered with this JEditoPane, if you need something more complicated you'll have to use thirdparty components请注意,只有某些 HTML 页面(相对简单的页面)可以使用此 JEditoPane 呈现,如果您需要更复杂的内容,则必须使用第三方组件

Based on OP's comment, I'm adding an update to the answer:根据 OP 的评论,我正在为答案添加更新:

Update更新

Since the HTMLs that you're trying to load are files inside the JAR, you should read the file into some string variable and use the aforementioned method setText由于您尝试加载的 HTML 是 JAR 中的文件,因此您应该将文件读入某个字符串变量并使用上述方法setText

Note that you shouldn't use java.io.File because it used to identify resources at the filesystem, and you're trying to access something inside the artifact:请注意,您不应使用java.io.File ,因为它用于识别文件系统中的资源,并且您正在尝试访问工件内部的某些内容:

Reading the resource like this can be done with the following construction:像这样读取资源可以通过以下结构来完成:

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);

Read Here about many different ways to read InputStream into String 在此处阅读有关将 InputStream 读入 String 的许多不同方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM