Reputation: 68847
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
Upvotes: 6
Views: 9240
Reputation: 1
JLabel label = new JLabel("Text");
frame.add(label , SwingConstants.CENTER);
Upvotes: 0
Reputation: 324098
Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.
Upvotes: 0
Reputation: 41580
In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.
Upvotes: 1
Reputation: 160954
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
Upvotes: 12