Java 使字符串在矩形中居中

Java 使字符串在矩形中居中,java,swing,Java,Swing,我有矩形的坐标要画,我想把一些文本放在这个矩形的中心 int x, y, width, height; String str = "This is a text"; x = 15; y = 15; width = 20; heights = 30; g.drawRect(x, y, width, height); g.drawString(str, x + width/2, y + height/2); 医生说 public abstract void drawString(String

我有矩形的坐标要画,我想把一些文本放在这个矩形的中心

int x, y, width, height;
String str = "This is a text";

x = 15;
y = 15;
width = 20;
heights = 30;

g.drawRect(x, y, width, height);
g.drawString(str, x + width/2, y + height/2);
医生说

public abstract void drawString(String theString,
              int x,
              int y)
Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.
The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system.
所以。。。您正在从矩形的中心点开始绘制字符串,但不是字符串


https://docs.oracle.com/javase/7/docs/api/java/awt/FontMetrics.html
-从gc获取字体度量,并计算字符串的宽度。然后从起点x减去一半。对y执行类似操作(请记住,高度不是从底部开始的。)

如果要将文本居中,则需要知道文本的长度,以便知道其相对于矩形宽度的宽度。这是通过从图形对象获取
FontMetrics
实例来完成的

因此,基本准则是:

FontMetrics fm = g.getFontMetrics();
int stringWidth = fm.getStringWidth(...);
int xDiff = (width - stringWidth) / 2;
g.drawString(str, x + xDiff, ...);

当然,您还需要基于高度居中。

因为宽度/高度的值为零,所以该代码不起任何作用。因此没有矩形可供绘制。张贴一个适当的说明问题的帖子。现在清楚问题是什么吗?