【问题标题】:How to add text different color on JTextPane如何在 JTextPane 上添加不同颜色的文本
【发布时间】:2011-08-29 10:20:38
【问题描述】:

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

【问题讨论】:

    标签: java swing jtextpane


    【解决方案1】:

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

    看这里:Style Tutorial

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

    【讨论】:

      【解决方案2】:

      【讨论】:

      • +1 是第一个链接到 Swing 教程的海报,该教程包含一个使用样式的工作示例。
      【解决方案3】:

      你可以使用 HTML 来做

      textPane.setContentType("text/html");
      

      【讨论】:

        猜你喜欢
        • 2012-08-17
        • 1970-01-01
        • 2012-01-20
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多