Java Swing How to - Change JTextPane text style








Question

We would like to know how to change JTextPane text style.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/*from   w  ww .j a  va  2s  .  com*/
public class Main {
  public static void main(String[] args) {

    JTextPane textPane = new JTextPane();
    textPane.setText("This is a test string");

    StyleConstants.setBold(BOLD, true);

    StyleConstants.setItalic(ITALIC, true);

    int start = 5;
    int end = 10;

    textPane.getStyledDocument().setCharacterAttributes(start, end - start,
        BOLD, false);
    textPane.getStyledDocument().setCharacterAttributes(start, end - start,
        ITALIC, false);
    for (int i = start; i < end; i++)
      System.out.println(textPane.getStyledDocument().getCharacterElement(i)
          .getAttributes().containsAttributes(BOLD)); // all now print true
    


    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JScrollPane(textPane));
    frame.pack();
    frame.setVisible(true);
  }

  private static final MutableAttributeSet BOLD = new SimpleAttributeSet();
  private static final MutableAttributeSet ITALIC = new SimpleAttributeSet();
}