I'm making a game engine based on Java Swing and I wonder if I can get the text width/height.

Say, what I have is:

  • the text string
  • the font and text size (the Font object)

What I've done is:

  • g.drawString(...)

What I want to know is:

  • the width/height of the text that displayed on the screen

1 Answer 1


Graphics returns FontMetrics that have method getStringBounds (and other usefull methods):

Rectangle2D r = graphics.getFontMetrics().getStringBounds(string, graphics);

With r you can for example render background for text and then render text.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .