How to center a drawString in Java? [closed]

2019-01-27 12:12发布

问题:

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?

回答1:

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

Also have a look at 2D Graphics and Working with Text APIs