shybovycha
shybovycha

Reputation: 12265

Displaying HTML with Java

Greetings!

I've been trying to display some HTML with Java using JEditorPane. But i've encountered a problem: it does not display any images.

I have a simple JFrame form with JButton and JEditorPane on it. Button has this click handler:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{
    String s = jEditorPane1.getText();

    if (jEditorPane1.getContentType() == "text/html")
        jEditorPane1.setContentType("text/plain"); else
            jEditorPane1.setContentType("text/html");

    jEditorPane1.setText(s);
}

This "converts" plain text to html and back when clicked. And this works perfectly for simple html. But when i try to show some images (giving image is inside directory with .jar i'm executing) i get image not found picture. The same happens when i put image inside my .jar.

So, the question is: How this could be fixed?

And one more to go: can i put some HTMLs with their files directories including inside my (or a new one) .jar and then show them up being loaded from that one? If so, how this can be done?

Upvotes: 1

Views: 5521

Answers (1)

JB Nizet
JB Nizet

Reputation: 691973

Regarding your first question : since you gave the HTML text directly to the editor pane, without asking to load it from a URL, it doesn't know how to resolve the relative URLs.

You thus have two solutions :

  1. use absolute URLs for your images
  2. tell the JEditorPane the base URL it must use to load resources.

For the second solution, you just have to obtain the HTMLDocument instance used by the editor pane, and call the setBase() method.

Regarding your second question, you may of course place HTML and images in the jar file, call Class.getResource() to get a URL of one of these HTML files, and give the URL to the editor pane : it will load the HTML and display images relatively to the URL of the loaded HTML file.

Upvotes: 1

Related Questions