Search code examples
javastringuser-interfacelabelgraphics2d

Graphics2D get String's dimension before drawing


In my program, I'm drawing a String like this:

graphics2D.drawString(string, x, y);

However, in order to determine the x and y, I would like to know the dimension (height and width) which this string is going have. How can I do this?


Solution

  • You need to use the FontMetrics class for that. You can get the FontMetrics to use from the Graphics object, and then use the stringWidth and getHeight methods to get the size.

    FontMetrics fm   = graphics2D.getFontMetrics();
    int stringWidth  = fm.stringWidth(string);
    int stringHeight = fm.getHeight();