Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Fonts and Pixels

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

like image 422
Martijn Courteaux Avatar asked Sep 09 '09 12:09

Martijn Courteaux


People also ask

What font does Java use?

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.

What is font metrics in Java?

The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.

Can you change font in Java?

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.

How do I change font size in Java?

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.


2 Answers

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
like image 85
coobird Avatar answered Sep 19 '22 14:09

coobird


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

like image 36
Lucas Gabriel Sánchez Avatar answered Sep 18 '22 14:09

Lucas Gabriel Sánchez