如何在Java中居中drawString? [英] How to center a drawString in Java?

查看:1224
本文介绍了如何在Java中居中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();

还演示了在这里

另请参阅 2D图形使用文本API

这篇关于如何在Java中居中drawString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆