如何在图形上绘制带有背景的字符串?

13

我使用Graphics.drawString绘制文本,但是我想要在矩形背景上绘制字符串。

2个回答

31

在绘制文本之前,请使用Graphics.fillRectGraphics2D.fill

以下是一个示例:

import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class FrameTestBase extends JFrame {
    public static void main(String args[]) {
        FrameTestBase t = new FrameTestBase();
        t.add(new JComponent() {
            public void paintComponent(Graphics g) {
                String str = "hello world!";
                Color textColor = Color.WHITE;
                Color bgColor = Color.BLACK;
                int x = 80;
                int y = 50;

                FontMetrics fm = g.getFontMetrics();
                Rectangle2D rect = fm.getStringBounds(str, g);

                g.setColor(bgColor);
                g.fillRect(x,
                           y - fm.getAscent(),
                           (int) rect.getWidth(),
                           (int) rect.getHeight());

                g.setColor(textColor);
                g.drawString(str, x, y);
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 200);
        t.setVisible(true);
    }
}

enter image description here


6

建议:

  • 使用JLabel
  • 通过调用setOpaque(true);方法来设置其不透明属性
  • 通过调用setForeground(myForegroundColor);方法来设置其前景色
  • 再通过调用setBackground(myBackgroundColor);方法来设置其背景色

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接