How to display an image in a JEditorPane using HTML

If you ever need to display an image in a Java JEditorPane, where that JEditorPane contains HTML content, this solution should work:

package com.valleyprogramming.type

import javax.swing._
import java.awt._

class HelpPanel extends JPanel {

    val prefsFileAsString = this.getClass.getResource("preferences.jpg").toString
    val prefsImgTag = s"<img src='$prefsFileAsString' />"
    val htmlContent = s"<html><p>Foo bar baz</p><p>$prefsImgTag</p></html>"
     
    val desiredSize = new Dimension(800, 600)
    val helpPane = new JEditorPane("text/html", htmlContent)
    helpPane.setEditable(false)
    helpPane.setMinimumSize(desiredSize)
    helpPane.setPreferredSize(desiredSize)
    val scrollPane = new JScrollPane(helpPane)
    this.setLayout(new BorderLayout)
    this.add(scrollPane, BorderLayout.CENTER)

}

That code is written in Scala rather than Java, but as you can see, it translates easily to Java.

One point to note about that code is that the file preferences.jpg should be in the same directory as the HelpPanel.class file. Because the package for the class is com.valleyprogramming.type, this just means that the preferences.jpg file should be in that directory when your code is compiled. (A great benefit of this approach is that it works just fine when your application is bundled up in a Jar file.)

For testing purposes you can easily display that HelpPanel using using a JOptionPane, like this:

JOptionPane.showMessageDialog(
    myJFrame,
    new HelpPanel,
    "Help",
    JOptionPane.PLAIN_MESSAGE)

In summary, if you need to display an image in some HTML in a JEditorPane component in a Java or Scala application, I hope this has been helpful.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.