Java - FontMetrics without Graphics

piotrek picture piotrek · May 16, 2010 · Viewed 18k times · Source

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

Answer

Lonzak picture Lonzak · Aug 8, 2013

No you do not necessarily need to get/use the graphics object:

Font font = new Font("Helvetica",Font.PLAIN,12);
Canvas c = new Canvas();
FontMetrics fm = c.getFontMetrics(font);

If you now call c.getGraphics() it will return null. Instead canvas will also work in headless mode.