Java center text in rectangle

Luka Tiger picture Luka Tiger · Jan 11, 2013 · Viewed 23.6k times · Source

I use drawString() method to draw string using Graphics, but I want to center my text in a rectangle. How should I do that?

Answer

Gilbert Le Blanc picture Gilbert Le Blanc · Jan 11, 2013

I've used this to center text on a JPanel

        Graphics2D g2d = (Graphics2D) g;
        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D r = fm.getStringBounds(stringTime, g2d);
        int x = (this.getWidth() - (int) r.getWidth()) / 2;
        int y = (this.getHeight() - (int) r.getHeight()) / 2 + fm.getAscent();
        g.drawString(stringTime, x, y);