This will print out "BLAH BLEG" in two different colors.
public class Main {
public static void main(String[] args) {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
try { doc.insertString(doc.getLength(), "BLAH ",style); }
catch (BadLocationException e){}
StyleConstants.setForeground(style, Color.blue);
try { doc.insertString(doc.getLength(), "BLEH",style); }
catch (BadLocationException e){}
JFrame frame = new JFrame("Test");
frame.getContentPane().add(textPane);
frame.pack();
frame.setVisible(true);
}
}
Look here: Style Tutorial
and check the section labeled: An Example of Using a Text Pane for a great example of how to dynamically change the colors.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…