【问题标题】:How to use multiple colors when using drawString() in java.awt.graphics?在 java.awt.graphics 中使用 drawString() 时如何使用多种颜色?
【发布时间】:2014-05-11 09:35:58
【问题描述】:

好的,问题来了。

g.setColor(Color.WHITE);
g.drawString("all your base belong to us",x,y);

下面的代码使得显示的字符串是白色的并且是全白的。

我的目标是制作字符串的某个部分,例如,我希望该字符串中的单词“base”是不同的颜色,在这种情况下为黄色。

我最可能使用的代码是:

g.drawString("all your #ffd700base belong to us",x,y);

该代码尝试将文本从“base”一直设置为黄色。

虽然它的输出是:

http://i.stack.imgur.com/lB2WC.png

忽略背景,只看字符串。 “#ffd700”成为字符串的一部分,然后显示出来。

这不起作用,我找不到可行的解决方案。

【问题讨论】:

  • 我认为你不能在 1 行中做到这一点。从javadoc g.drawString Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system. 所以你需要设置一个颜色,写一段文字,设置颜色#ffd700,再画一段文字等等......
  • Aww,这太糟糕了,因为我必须创建一个新的 Graphics 对象,将 x 和 y 设置为比上一条消息多一点。不管怎样,我会留意是否有更多的解决方案。

标签: java graphics


【解决方案1】:

同样的问题在这里解决了。请看下面的帖子:

上面链接中提到的代码经过一些更改后的示例代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.CellRendererPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class PaintComponentTest extends JPanel {

    private static final String s = "<html>all your <font color=\"#ffd700\">base</font> belong to us</html>";
    private JLabel renderer = new JLabel(s);
    private CellRendererPane crp = new CellRendererPane();
    private Dimension dim;

    public PaintComponentTest() {
        this.setBackground(Color.lightGray);
        dim = renderer.getPreferredSize();
        this.add(crp);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        renderer.setForeground(Color.WHITE);
        crp.paintComponent(g, renderer, this, 10, 10, dim.width, dim.height);
    }

    private void display() {
        JFrame f = new JFrame("PaintComponentTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(this);
        f.pack();
        f.setSize(200, 70);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new PaintComponentTest().display();
            }
        });
    }
}

截图:

【讨论】:

  • 这不起作用,即使我将 Graphics 转换为 graphics2d 并创建一个名为 g2 的对象然后使用 html,它也使用 html。
猜你喜欢
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2021-11-25
  • 2020-05-09
  • 2016-09-25
  • 2012-03-23
  • 2016-11-15
  • 1970-01-01
相关资源
最近更新 更多