JTextPane formatting [closed]

Also seen here, TextComponentDemo shows how to apply a number of StyleConstants, including font size, style, alignment and color. The styles may applied either directly to the Document, as shown in initAttributes(), or via the actions of StyledEditorKit, seen here.

Addendum: The example below creates three related styles using SimpleAttributeSet. Note that highAlert alters the color but retains the bold attribute inherited from boldBlue.

image

import java.awt.Color;
import java.awt.EventQueue;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
 * @see https://stackoverflow.com/a/15600689/230513
 */
public class Test {

    private void display() throws BadLocationException {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String s = new Date().toString();
        JTextPane jtp = new JTextPane();
        StyledDocument doc = (StyledDocument) jtp.getDocument();

        SimpleAttributeSet normal = new SimpleAttributeSet();
        StyleConstants.setFontFamily(normal, "SansSerif");
        StyleConstants.setFontSize(normal, 16);

        SimpleAttributeSet boldBlue = new SimpleAttributeSet(normal);
        StyleConstants.setBold(boldBlue, true);
        StyleConstants.setForeground(boldBlue, Color.blue);

        SimpleAttributeSet highAlert = new SimpleAttributeSet(boldBlue);
        StyleConstants.setFontSize(highAlert, 18);
        StyleConstants.setItalic(highAlert, true);
        StyleConstants.setForeground(highAlert, Color.red);

        doc.insertString(doc.getLength(), s + "\n", normal);
        doc.insertString(doc.getLength(), s + "\n", boldBlue);
        doc.insertString(doc.getLength(), s + "\n", highAlert);
        f.add(jtp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new Test().display();
                } catch (BadLocationException ex) {
                    ex.printStackTrace(System.err);
                }
            }
        });
    }
}

Leave a Comment