16

任何人都可以帮助我简单的日志,我必须在 JTextPane 日志消息的第一行添加所选颜色(绿色正常,红色失败)。如何做到这一点?

4

3 回答 3

36

这将以两种不同的颜色打印出“BLAH BLEG”。

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);
    }
}

看这里:风格教程

并检查标记为:使用文本窗格的示例,以获取有关如何动态更改颜色的一个很好的示例。

于 2011-05-20T07:30:33.943 回答
10

对于JTextPane ,您可以在http://www.java2s.com/Code/Java/Swing-JFC/TextPane.htm上实现StyledDocument一些示例

于 2011-05-20T07:12:09.963 回答
0

您可以为此使用 HTML,然后执行

textPane.setContentType("text/html");
于 2015-02-21T20:24:43.313 回答