有人能帮我处理简单的日志吗?我需要在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);
}
}
请看这里:样式教程
并查看标注为使用文本窗格的示例部分,以获取如何动态更改颜色的绝佳示例。
你可以使用HTML来实现,然后执行
textPane.setContentType("text/html");