简体   繁体   中英

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. I try loading my html into a Jeditorpanel but it can't seem to work.

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

Based on OP's comment, I'm adding an update to the answer:

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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