【问题标题】:change specific text color in java在java中更改特定的文本颜色
【发布时间】:2012-03-13 01:51:45
【问题描述】:

我想知道如何更改句子中的特定文本颜色?

让我们说 HELLO WORLD...我想在不改变 HELLO 的字体颜色的情况下将 WORLD 更改为红色......关于如何将 WORLD 更改为粗体的完全相同的事情

我想将这些字符串设置为 jtextarea,但我能找到的只是这样的

JTextArea textbox = new JTextArea("hello world");
textbox.setForeground(Color.red)

这些让整个句子变成红色,而不是只让 WORLD 变成红色?

【问题讨论】:

    标签: java string swing text colors


    【解决方案1】:

    查看 Oracle 文档中有关文本组件的 thisJTextArea 将接受样式,但它将始终在其整个内容中应用样式。但是,如果您要使用 JTextPane,您可以使用 HTML 在文本中创建您想要的任何样式。

    备份断言的代码:

    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.html.HTMLEditorKit;
    
    public class StyleTestApp {
        public static void main(final String[] args) {
            final JFrame f = new JFrame("test");
            //f.getContentPane().add(new JTextArea("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>"));
            final JTextPane p = new JTextPane();
            // the HTMLEditorKit is not enabled by default in the JTextPane class.
            p.setEditorKit(new HTMLEditorKit());
            p.setText("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>");
            f.getContentPane().add(p);
            f.pack();
            f.setVisible(true);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 2012-12-19
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多