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

    new HelpPanel,

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.