Inserting Styled Text in a JTextPane Component - Java Swing

Java examples for Swing:JTextPane

Description

Inserting Styled Text in a JTextPane Component

Demo Code

import java.awt.Color;

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[] args) throws Exception {
    try {/*from w  ww  .j a  v  a2s.c om*/
      JTextPane textPane = new JTextPane();
      StyledDocument doc = (StyledDocument) textPane.getDocument();

      // Create a style object and then set the style attributes
      Style style = doc.addStyle("StyleName", null);

      // Italic
      StyleConstants.setItalic(style, true);

      // Bold
      StyleConstants.setBold(style, true);

      // Font family
      StyleConstants.setFontFamily(style, "SansSerif");

      // Font size
      StyleConstants.setFontSize(style, 30);

      // Background color
      StyleConstants.setBackground(style, Color.blue);

      // Foreground color
      StyleConstants.setForeground(style, Color.white);

      // Append to document
      doc.insertString(doc.getLength(), "Some Text", style);
    } catch (BadLocationException e) {
    }
  }
}

Related Tutorials