Java Swing How to - Insert images in JEditorPane using pane.getDocument.insert()








Question

We would like to know how to insert images in JEditorPane using pane.getDocument.insert().

Answer

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
//from w  w w .  j a  v  a  2  s  .  c  o m
public class Main {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    JEditorPane edPane = new JEditorPane();
    edPane.setContentType("text/html");

    HTMLEditorKit hek = new HTMLEditorKit();

    edPane.setEditorKit(hek);

    HTMLDocument doc = (HTMLDocument) edPane.getDocument();

    doc.insertString(0, "Test testing", null);

    Element[] roots = doc.getRootElements();
    Element body = null;
    for (int i = 0; i < roots[0].getElementCount(); i++) {
      Element element = roots[0].getElement(i);
      if (element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.BODY) {
        body = element;
        break;
      }
    }

    doc.insertAfterEnd(body,"<img src=" + ClassLoader.getSystemResource("thumbnail.png").toString()
            + ">");
    frame.add(edPane);

    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}