简体   繁体   中英

How to draw String with background on Graphics?

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

Use Graphics.fillRect or Graphics2D.fill before drawing the text.

Here's an example:

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);
    }
}

在此输入图像描述

Suggestion:

  • Use a JLabel
  • Set its opaque property to true via setOpaque(true);
  • Set its foreground color via setForeground(myForegroundColor);
  • Then set its background color via setBackground(myBackgroundColor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM