【发布时间】:2016-04-07 13:18:10
【问题描述】:
我想在面板上获取字符串的确切高度(以像素为单位)。所以我写了一个程序,绘制字符串,然后在它周围画一个矩形。
使用 FontMetrics 我使用 getStringBounds 方法来获取封闭矩形。
但是看起来不对:
我原以为矩形可以完美地包围我的文本,但顶部有空间(左右两侧还有一点空间)。为什么它会给我这个结果?
这是我的代码:
public class Test extends JPanel {
@Override
protected void paintComponent(Graphics g) {
Font font = new Font("Arial", Font.PLAIN, 60);
g.setFont(font);
FontMetrics fm = this.getFontMetrics(font);
String str = "100dhgt";
Rectangle2D rect = fm.getStringBounds(str, g);
int x = 5;
int y = 100;
g.drawRect(x, y - (int)rect.getHeight(), (int)rect.getWidth(), (int)rect.getHeight());
g.drawString(str, x, y);
}
public static void main(String[] args) {
JFrame f = new JFrame();
Test test = new Test();
f.add(test);
f.setVisible(true);
f.setSize(400, 400);
}
}
【问题讨论】: