Search code examples
javajava-2dfontmetrics

Java: Friendlier way to get an instance of FontMetrics


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.


Solution

  • The really correct answer is to use Toolkit.

    Font font = new Font("Courier New", Font.PLAIN, 14);
    FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);