14

Can anybody help me with simple log, I have to add at first line on JTextPane log messages with chosen color ( green ok, red failure ). How to achieve this ?

Stephen Docy
  • 4,598
  • 6
  • 16
  • 30
Almira Bojani
  • 517
  • 2
  • 10
  • 19

3 Answers3

34

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.

jwueller
  • 28,909
  • 4
  • 60
  • 69
Snukus
  • 1,242
  • 9
  • 17
10

for JTextPane you can implements StyledDocument some examples for that on http://www.java2s.com/Code/Java/Swing-JFC/TextPane.htm

mKorbel
  • 108,320
  • 17
  • 126
  • 296
  • 1
    +1 for being the first poster to link to the Swing tutorial which contains a working example that uses Styles. – camickr May 20 '11 at 15:26
0

You can use HTML for that and then do

textPane.setContentType("text/html");
Community
  • 1
  • 1
Kai Arakawa
  • 187
  • 1
  • 1
  • 13