Search code examples
javagraphics2d

How to find the dimensions of a string that you are drawing with graphics2d?


I am trying to paint a caret at the end of a string but I do not know how to retrieve the dimensions of the given string I am painting with graphics2d.drawString. Or if there is a "shape" that is actually a string with dimensions, that would help to, thanks..


Solution

  • You can try something like this

    Graphics2D g2d = ...
    Font font = ...
    Rectangle2D r = font.getStringBounds("Your_String!", g2d.getFontRenderContext());
    System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");