Inserting a Component into a JTextPane Component - Java Swing

Java examples for Swing:JTextPane

Description

Inserting a Component into a JTextPane Component

Demo Code

import javax.swing.JButton;
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 void main(String[] argv) {
    try {/*from  w  ww .  j a v  a 2 s  .  c  o m*/
      JTextPane textPane = new JTextPane();
      StyledDocument doc = (StyledDocument) textPane.getDocument();

      // The component must first be wrapped in a style
      Style style = doc.addStyle("StyleName", null);
      StyleConstants.setComponent(style, new JButton("OK"));

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

Related Tutorials