如何在JTextPane上添加不同颜色的文本

17

有人能帮我处理简单的日志吗?我需要在JTextPane日志消息的第一行添加选定颜色(绿色表示成功,红色表示失败)。怎么实现这个功能呢?

3个回答

37

这将以两种不同颜色打印出"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);
    }
}

请看这里:样式教程

并查看标注为使用文本窗格的示例部分,以获取如何动态更改颜色的绝佳示例。


10

1
+1 鼓励第一个发布链接到包含使用样式的工作示例的 Swing 教程的用户。 - camickr

0

你可以使用HTML来实现,然后执行

textPane.setContentType("text/html");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接