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
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
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
Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.