2011-04-20 112 views
1

如何计算px中字符串的宽度?我有面板,我尝试像(此参考JPanel)如何计算px中字符串的宽度?

FontMetrics gp = this.getGraphics().getFontMetrics(); 
int x=gp.stringWidth("test"); 

但getGraphics返回始终为空,因为面板不可见。如何解决这个问题呢 ?

+1

忘记方法component.getGraphics() - 你不需要它:要么你已经有了一个Graphics对象(作为参数传入,在paintComponent中是fi),或者你不应该使用它;-) – kleopatra 2011-04-21 06:37:54

回答

5

您应该在存在Graphics实例的paint()paintComponent()方法之一中执行此操作。您可以创建一个BufferedImage并致电getGraphics()