Inserting an Image into a JTextPane Component - Java Swing

Java examples for Swing:JTextPane

Description

Inserting an Image into a JTextPane Component

Demo Code

import javax.swing.ImageIcon;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String[] argv) {
    try {//from ww  w  .j a v  a 2  s. c o m
      // Get the text pane's document
      JTextPane textPane = new JTextPane();
      StyledDocument doc = (StyledDocument) textPane.getDocument();

      // The image must first be wrapped in a style
      Style style = doc.addStyle("StyleName", null);
      StyleConstants.setIcon(style, new ImageIcon("imagefile"));

      // Insert the image at the end of the text
      doc.insertString(doc.getLength(), "ignored text", style);
    } catch (BadLocationException e) {
    }
  }
}

Related Tutorials