I use drawString()
method to draw string using Graphics, but I want to center my text in a rectangle. How should I do that?
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);