Damir
Damir

Reputation: 56249

How to calculate width of string in px?

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");

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

Upvotes: 1

Views: 533

Answers (1)

StanislavL
StanislavL

Reputation: 57421

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().

Upvotes: 5

Related Questions