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

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

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

看这里: 样式教程

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

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

您可以使用HTML然后执行此操作

 textPane.setContentType("HTML/plain");