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

时间:2011-05-20 06:47:43

标签: java swing jtextpane

任何人都可以通过简单的日志帮助我,我必须在第一行添加选择颜色的JTextPane日志消息(绿色确定,红色失败)。怎么做到这一点?

3 个答案:

答案 0 :(得分:31)

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

请看这里:Style Tutorial

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

答案 1 :(得分:9)

答案 2 :(得分:0)

您可以使用HTML,然后执行

textPane.setContentType("HTML/plain");
相关问题