更改抽象字符串中的文本颜色()

Chr*_*and 7 java swing awt java-2d styledtext

我正在尝试使用swing来强调字符串中的一个作品.

建议我使用以下代码的HTML:

Graphics2D g2 = (Graphics2D) g;
g.drawString("this is something I want people to <p color="#00FF00">NOTICE</p>", x, y);
Run Code Online (Sandbox Code Playgroud)

我试过这个,但没有运气......它只是输出HTML

谁能指出我正确的方向?

Dav*_*amp 10

  • 请问这个编译:g.drawString("this is something I want people to <p color="#00FF00">NOTICE</p>", x, y);如'"是一个特殊的字符,我们必须逃跑呢\

  • 您转换为Graphics2D但不使用它(与问题无关但可能导致异常).

它应该是:

Graphics2D g2 = (Graphics2D) g;
g2.drawString("this is something I want people to <p color=\"#00FF00\">NOTICE</p>", x, y);
Run Code Online (Sandbox Code Playgroud)

以增添色彩简单地调用setColor(Color c)Graphic对象s:

g2.setColor(Color.GREEN);
Run Code Online (Sandbox Code Playgroud)

但是,如果您只想将部分绘制为绿色JLabel用于HTML支持(最多为HTML3.2),则会将整个String设置为绿色.

JLabel label = new JLabel("<html>this is something I want people to <p color=\"#00FF00\">NOTICE</p></html>");
Run Code Online (Sandbox Code Playgroud)

完整的例子:

在此输入图像描述

NB你可以看到通知是在它自己的行上那是因为段落标签而不是使用字体标签将它放在一行上,如下所示:

在此输入图像描述

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Test {

    public Test() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("<html>this is something I want people to <p color=\"#00FF00\">NOTICE</p></html>");

        // JLabel label = new JLabel("<html>this is something I want people to <font color=\"#00FF00\">NOTICE</font></html>");//will be shown on single line

        frame.add(label);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)