Add colored text to the document : SimpleAttributeSet « Swing « Java Tutorial

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
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 extends JTextPane {

  public void append(Color c, String s) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    int len = getDocument().getLength();
    setCharacterAttributes(aset, false);

  public static void main(String argv[]) {
    Main pane = new Main();
    for (int n = 1; n <= 4; n += 1) {
        pane.append(, String.valueOf(n) + ' ');
    JFrame f = new JFrame("ColorPane example");
    f.setContentPane(new JScrollPane(pane));
    f.setSize(600, 400);


14.39.1.Creating Styled Text: Using a SimpleAttributeSet
14.39.2.Using StyleConstants class to simplify style sttribute settings
14.39.3.Add colored text to the document
14.39.4.Use SimpleAttributeSet with JTextPane
14.39.5.Tests two attributed strings for equality.