1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This one was helpful. But the second question was about runtime file adding. Is it possible? I mean is it possible to store HTML files and all the stuff within my .jar which is running and how this can be done?
Yes it is possible. Just make sure you store them in the right paths in the Jar so that the relative references to images (and stylesheets etc.) can be resolved. An URL to the HTML can be obtained using this.getClass().getResource("path/to/the.html"). Use that URL for the JEditorPane and everything should work (as well as it will ever work in a JEditorPane).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.