Is there a way, using g.drawString(), to automatically center text instead of trying to guess and check?
Thanks,
-Nathan
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
Right so if you use FontMetrics as the above poster stated, you can think about it like this:
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);