How to add text different color on JTextPane

情到浓时终转凉″ 提交于 2019-11-26 11:11:32

问题


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 ?


回答1:


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

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:


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




回答3:


You can use HTML for that and then do

textPane.setContentType("HTML/plain");


来源:https://stackoverflow.com/questions/6068398/how-to-add-text-different-color-on-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!