views:

84

answers:

1

I'm trying to center a string drawn with a ""system", Font.BOLD, 90" font in Java. I've tried (width/2 - (font.size/2 * num_of_chars)) but that didn't work.

g2d.setFont(new Font("system", Font.BOLD, 90));
g2d.drawString("Pause", (int) ((800/2) - ((Font.getSize()/2) * 5)),270);
+3  A: 

Use getFontMetrics().getStringBounds(String, Graphics) to get the bounds of the string with the current font.

So it would look something like this:

g2d.setFont(new Font("system", Font.BOLD, 90));
String msg = "Pause";
Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(msg, g2d);
g2d.drawString(msg, (int) ((getWidth() + bounds.getWidth()) / 2), 270);
Michael Myers
Is there a way to get getStringBounds() to return a rect instead of a rect2D?
William
edit: nevermind. I see that 2D has a getWidth method too. Thanks.
William