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