Java Swing How to - Set style for JTextPane








Question

We would like to know how to set style for JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
/* w  w w  . ja  v a 2s  .c  o  m*/
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class Main {
  public static void main(String... args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
        StyleConstants.Foreground, Color.RED);
    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");

    JTextPane tPane1 = new JTextPane();
    tPane1.setCharacterAttributes(aset, false);

    f.add(tPane1, BorderLayout.CENTER);

    f.pack();
    f.setVisible(true);
  }
}