Centering text in a JFrame

Is there a way, using g.drawString(), to automatically center text instead of trying to guess and check?

Thanks,

-Nathan

I’ve always done it by (for games at least)


FontMetrics metrics = graphics.getFontMetrics(yourFont);
Rectangle rect = metrics.getStringBounds(str, graphics); 

then using the JPanel size and performing a quick bit of math :slight_smile:

Right so if you use FontMetrics as the above poster stated, you can think about it like this:

  1. You have the Rectangle bounds for both the JPanel and the String.
  2. You know the center of each rectangle is the same point… because that is the center.
  3. You get the center point by dividing the width and height of the JPanel both by 2.
  4. Subtract from that point the halved width and height of the String, and boom, you have the location for the string to be drawn.

int strWidth = (int) rect.getWidth();
int strHeight = (int) rect.getHeight();
int pw = panel.getWidth();
int ph = panel.getHeight();

int centerX = pw/2;
int centerY = ph/2;

int strx = centerX - (strWidth/2);
int stry = centerY - (strHeight/2);

g.drawString(str, strx, stry);