How to add text different color on JTextPane

前端 未结 3 1924
轻奢々
轻奢々 2020-12-01 11:38

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 ?

相关标签:
3条回答
  • 2020-12-01 11:46

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

    0 讨论(0)
  • 2020-12-01 12:03

    You can use HTML for that and then do

    textPane.setContentType("text/html");
    
    0 讨论(0)
  • 2020-12-01 12:05

    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.

    0 讨论(0)
提交回复
热议问题