Search code examples
javastringcenter

Center a drawn string relative to the window size?


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);

Solution

  • 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);