Skip to content
Advertisement

Java – FontMetrics without Graphics

How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way:

BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
FontMetrics fm = bi.getGraphics().getFontMetrics(font);
int width = fm.stringWidth(pattern);
int height = fm.getHeight();

Advertisement

Answer

Hmm… It is quite logical that you need graphics to get FontMetrics. Font height, width etc. can differ on various displays.

If you have some Component, you can use it for getting FontMetrics:

component.getFontMetrics(font);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement