开发者

How to calculate width of string in px?

开发者 https://www.devze.com 2023-02-27 01:59 出处:网络
How to calculate width of string in px ? I have panel and I try like (this reference on JPanel) FontMetrics gp = this.getGraphics().getFontMetrics();

How to calculate width of string in px ? I have panel and I try like (this reference on JPanel)

FontMetrics gp = this.getGraphics().getFontMetrics();
int x=gp.stringWidth("test开发者_StackOverflow");

but getGraphics returns always null because panel isn't visible yet. How to solve this problem ?


You should do this in one of the paint() or paintComponent() methods where the Graphics instance exists.

Or you can can create a BufferedImage and call getGraphics().

0

精彩评论

暂无评论...
验证码 换一张
取 消