Java Swing How to - Style letter by letter for JTextPane








Question

We would like to know how to style letter by letter for JTextPane.

Answer

//w  w  w. j a  va  2s . co m
import java.awt.Color;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

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

    StyledDocument doc = new DefaultStyledDocument();
    JTextPane textPane = new JTextPane(doc);
    textPane.setText("this is a test.");

    Random random = new Random();
    for (int i = 0; i < textPane.getDocument().getLength(); i++) {
      SimpleAttributeSet set = new SimpleAttributeSet();
      StyleConstants.setForeground(
          set,
          new Color(random.nextInt(256), random.nextInt(256), random
              .nextInt(256)));
      StyleConstants.setFontSize(set, random.nextInt(12) + 12);
      StyleConstants.setBold(set, random.nextBoolean());
      StyleConstants.setItalic(set, random.nextBoolean());
      StyleConstants.setUnderline(set, random.nextBoolean());

      doc.setCharacterAttributes(i, 1, set, true);
    }

    frame.add(new JScrollPane(textPane));
    frame.setSize(500, 400);
    frame.setVisible(true);
  }

}