[英]How to draw String with background on Graphics?
我用Graphics.drawString绘制文本,但我想用矩形背景绘制字符串。
Use Graphics.fillRect
or Graphics2D.fill
before drawing the text. 在绘制文本之前使用
Graphics.fillRect
或Graphics2D.fill
。
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: 建议:
setOpaque(true);
setOpaque(true);
将其opaque属性设置为true setOpaque(true);
setForeground(myForegroundColor);
setForeground(myForegroundColor);
设置其前景色setForeground(myForegroundColor);
setBackground(myBackgroundColor);
setBackground(myBackgroundColor);
设置其背景颜色setBackground(myBackgroundColor);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.