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

时间:2023-01-27 16:24:02

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 ?

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

3 个解决方案

#1


31  

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

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

Look here: Style Tutorial

看这里:样式教程

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

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

#2


8  

for JTextPane you can implements StyledDocument some examples for that on http://www.java2s.com/Code/Java/Swing-JFC/TextPane.htm

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

#3


0  

You can use HTML for that and then do

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

textPane.setContentType("HTML/plain");

#1


31  

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

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

Look here: Style Tutorial

看这里:样式教程

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

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

#2


8  

for JTextPane you can implements StyledDocument some examples for that on http://www.java2s.com/Code/Java/Swing-JFC/TextPane.htm

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

#3


0  

You can use HTML for that and then do

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

textPane.setContentType("HTML/plain");