Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
Martijn Courteaux Avatar asked Nov 29 '22 18:11

Martijn Courteaux


1 Answers

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...

like image 152
Lonzak Avatar answered Dec 15 '22 04:12

Lonzak