[英]How to add text different color on 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);
}
}
看这里: 风格教程
并查看标签为:使用文本窗格的示例,了解如何动态更改颜色的一个很好的示例。
您可以为此使用 HTML,然后执行
textPane.setContentType("text/html");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.