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
Physical and Logical Fonts All implementations of the Java Platform must support TrueType fonts; support for other font technologies is implementation dependent. Physical fonts may use names such as Helvetica, Palatino, HonMincho, or any number of other font names.
The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.
Select General > Appearance > Colorsand Fonts (1) in the left pane. Select Java Editor Text Font (2) in the center. Click Edit… button in the right.
You can't actually change the size of an existing Font object. The best way to achieve a similar effect is to use the deriveFont(size) method to create a new almost identical Font that is a different size. Note: you need to specify that bigNumber is a float, otherwise you'll trigger the deriveFont(int style) overload.
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
In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With