【发布时间】:2018-10-24 09:53:10
【问题描述】:
实际上我有这些方法来获取字符串的宽度/高度大小,两者都需要绘制组件内的命令。但是我想在类构造函数中获取这些值。这可能吗?
public int getStringWidth(Graphics g){
g2d = (Graphics2D) g;
metrics = g2d.getFontMetrics(this.font);
return metrics.stringWidth(this.string);
}
public int getStringHeight(Graphics g){
g2d = (Graphics2D) g;
metrics = g2d.getFontMetrics(this.font);
int height = (int)font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight();
return height;
}
font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight() 这是我精确计算字符串高度大小的最佳命令,它也需要Graphics g。
【问题讨论】:
-
我在这段代码中使用 FontMetrics,需要
Graphics g才能工作 -
我删除了我之前不清楚的评论。见stackoverflow.com/questions/1524855/…
-
是的,您可以从 Graphics 以外的其他对象获取 FontMetrics 对象:例如 swing 组件。见docs.oracle.com/javase/7/docs/api/java/awt/class-use/…
-
“但是我想在类构造函数中获取这些值。” 为什么?见What is the XY problem?
-
@AndrewThompson,问题是我必须等待 1 次重绘才能获取 Sprites 值,而paintComponent 是在面板上绘制图形而不是初始化图形,我只是想在上面初始化图形类构造函数