如何在JTextPane上添加文本不同的颜色 [英] How to add text different color on JTextPane

查看:184
本文介绍了如何在JTextPane上添加文本不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anybody help me with simple log, I have to add at first line on JTextPane log messages with chosen color ( green ok, red failure ). How to achieve this ?

推荐答案

这将打印出两种不同颜色的BLAH BLEG。

This will print out "BLAH BLEG" in two different colors.

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);
    }
}

看这里:风格教程

并查看标记为的部分:使用文本窗格的示例是一个如何动态更改颜色的好例子。

and check the section labeled: An Example of Using a Text Pane for a great example of how to dynamically change the colors.

这篇关于如何在JTextPane上添加文本不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆