// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class JTP extends JFrame implements ActionListener {
    private JTextPane p;
    private JButton btn;
    public JTP() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Some JTextPane fun");
        getContentPane().setLayout(new BorderLayout());
        p = new JTextPane();
        getContentPane().add(p, BorderLayout.CENTER);
        btn = new JButton("Add som text in random attributes");
        btn.addActionListener(this);
        getContentPane().add(btn, BorderLayout.SOUTH);
        pack();
    }
    private Random rng = new Random();
    private static final Color[] cols = { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.BLACK, Color.WHITE, Color.ORANGE, Color.PINK, Color.CYAN, Color.MAGENTA };
    private static final String[] fontfam = { "Arial", "Arial Narrow", "Book Antiqua", "Century Gothic", "Courier New", "Lucida Sans", "Palatino Linotype", "SansSerif", "Serif", "Times New Roman", "Verdana" };
    @Override
    public void actionPerformed(ActionEvent e) {
        StyledDocument doc = p.getStyledDocument();
        try {
            MutableAttributeSet attrs = p.getInputAttributes();
            StyleConstants.setFontFamily(attrs, fontfam[rng.nextInt(fontfam.length)]);
            StyleConstants.setFontSize(attrs, 5 + rng.nextInt(20));
            System.out.println(StyleConstants.getFontSize(attrs));
            StyleConstants.setItalic(attrs, rng.nextDouble() > 0.5);
            StyleConstants.setBold(attrs, rng.nextDouble() > 0.5);
            StyleConstants.setForeground(attrs, cols[rng.nextInt(cols.length)]);
            StyleConstants.setBackground(attrs, cols[rng.nextInt(cols.length)]);
            doc.insertString(doc.getLength(), "Dette er en test\r\n", attrs);
            pack();
        } catch (BadLocationException e1) {
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JTP();
                f.setVisible(true);
            }
        });
    }
}
