Java: Fonts and Pixels

I am making a game and on the menu I want to display 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 a specified size and style.

Martine

+5
source share
4 answers

The method FontMetrics.stringWidthdoes just that - it will return the width in pixels for the given one String.

Can be obtained FontMetricsfrom the Graphicsobject getFontMetrics.

For example:

g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");

System.out.println(width);

The result is:

135
+11
source

In the Font class , you have methods like getLineMetrics or getStringBounds that can help you.

+1
source

JLabel , .

0
JLabel label = new JLabel("Text");

frame.add(label , SwingConstants.CENTER);
0
source

All Articles