How can I center the text of a drawString in Java? I want it to that it can be centered along the screen dynamically, whether I change the height and width of the box or not. I found this codebut I don't know how to use it. can someone explain?
解决方案
Horizontally...
String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
Vertically...
String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
Also demonstrated here