有谁能帮我做一个简单的日志,我必须在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");