views:

287

answers:

3

Hello,

I'm making a game and in the menu I want to display the text in the center of the screen. Is there a way in Java to get/calculate the width of a piece of text in a specified font with specified size and style.

Martijn

+10  A: 

The FontMetrics.stringWidth method does just that -- it will return the width in pixels for a given String.

One can obtain the FontMetrics from a Graphics object by the getFontMetrics method.

For example:

g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");

System.out.println(width);

The result was:

135
coobird
why is FontMetrics abstract??
Martijn Courteaux
thanks for the fast help.
Martijn Courteaux
FontMetrics is abstract because the result depends on the particular graphics object used.
Paul de Vrieze
+1  A: 

In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.

unkiwii
A: 

Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.

camickr