Java: Friendlier way to get an instance of FontMetrics

Martijn Courteaux picture Martijn Courteaux · May 2, 2010 · Viewed 7.5k times · Source

Is there a friendlier way to get an instance of FontMetrics than

FontMetrics fm = Graphics.getFontMetrics(Font);

I hate this way because of the following example:

If you want to create in a game a menu and you want all the menuitems in the center of the screen you need fontmetrics. But, mostly, menuitems are clickable. So I create an array of Rectangles and all the rectangles fits around the items, so when the mouse is pressed, I can simply use

for (int i = 0; i < rects.length; i++)
if (rects[i].contains(mouseX, mouseY)) { ... }

But to create the rects I also need FontMetrics for their coordinates. So this mean that I have to construct all my rectangles in the paint-method of my menu.

So I want a way to get the FontMetrics so I can construct the Rectangles in a method called by the constructor.

Answer

Lonzak picture Lonzak · Aug 9, 2013

For me the easiest way was to:

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

Benefits:

  1. If you call c.getGraphics() it will return null (thus there is no graphics object)
  2. This (canvas) will also work in headless mode.

Now you can easily get height and width...