在java中更改特定的文本颜色 [英] change specific text color in java

查看:222
本文介绍了在java中更改特定的文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在一个句子中更改特定的文字颜色?

i am wondering how can i change a specific text color in a sentence?

让我说HELLO WORLD ...我想把WORLD改成红色,而不改变HELLO..same的字体颜色如何改变WORLD到大胆的

lets say HELLO WORLD...i wanted to change the WORLD into red color without altering the font color of HELLO..same exact thing on how to change the WORLD in to bold

我想将这些字符串设置为一个jtextarea,但我可以找到是这样

i wanted to set these string in to a jtextarea but all i can find is something like this

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

这些使整个句子变成红色,而不是只有将WORLD变成红色吗?

these makes the whole sentence into red instead of only making WORLD into red?

推荐答案

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

Have a look at this this from the Oracle documentation on text components. A JTextArea will accept styling, but it will always apply styling across its entire contents. However, if you were to use a JTextPane, you could create any styling you wanted in your text using 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);
    }
}

这篇关于在java中更改特定的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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