Martijn Courteaux
Martijn Courteaux

Reputation: 68847

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

Upvotes: 6

Views: 9240

Answers (4)

Guest
Guest

Reputation: 1

JLabel label = new JLabel("Text");

frame.add(label , SwingConstants.CENTER);

Upvotes: 0

camickr
camickr

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

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

Upvotes: 1

coobird
coobird

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

Related Questions