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 ?
You should do this in one of the
paint()orpaintComponent()methods where theGraphicsinstance exists.Or you can can create a
BufferedImageand callgetGraphics().