600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > drawstring 文本居中 如何在Java中居中drawString?

drawstring 文本居中 如何在Java中居中drawString?

时间:2020-09-21 04:30:43

相关推荐

drawstring 文本居中 如何在Java中居中drawString?

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。