如何让 JLabel 准确预测它的宽度?
我遇到一种情况,用户输入一个字符串,我的代码为其创建一个 Jlabel 并尝试将其置于全屏 JFrame/Pane 的中心。我的问题是,为了能够准确地将其居中,我需要知道它的尺寸。
我需要一种方法来确定 JLabel 应该有多长(宽),以便它能够容纳字符串的长度,仅此而已。我尝试使用组件具有的 PreferredSize() 方法,但它看起来很糟糕(我传递了一个空值来让我的 UI 确定 PreferredSize)。我知道如何计算出有效的高度(fontSize + 10px 的大小通常很好),但我无法获得宽度。
我正在使用绝对定位(没有布局管理器)。
谢谢
I have a situation where a user enters a String and my code makes a Jlabel for it and attempts to center it on a full screen JFrame/Pane. My problem is, to be able to accurately center it, I need to know its dimensions.
I need a way to figure out how long (wide) the JLabel should be so that it accomodates the length of the string and nothing more. I tried using the preferredSize() method that components have and it looked horrible (I passed a null value to let my UI determine the preferredSize). I know how to figure out the height that works (the size of the fontSize + 10px is usually good) but I can't get the width.
I am using absolute positioning (no LayoutManager).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信如果您没有事先设置的话,实际宽度来自
getPreferredSize().getWidth()
。尝试输出首选大小而不将其设置为 null。使用 MigLayout 将组件居中时,我通常使用pref!
使所有尺寸的组件尽可能小并避免包裹,然后将其置于宽敞的父容器中居中。I believe the actual width comes from
getPreferredSize().getWidth()
if you don't set it beforehand. Try outputting the preferred size without setting it to null. With MigLayout when centering components, I normally usepref!
to make the component as small as possible for all sizes and avoid wrapping, and then center it in the spacious parent container.如果您已经使用字体
height + 10
作为高度,则可以轻松使用字符串width + x
。您将使用
FontMetrics
:If you are already using the font
height + 10
for height, you can easily use the stringwidth + x
.You will use
FontMetrics
:通过使用一些 LayoutManager 检查此 如何确定图形字符串的长度?
by using some of LayoutManagers check this How to determine the length of a graphic string?
我强烈建议您为 GUI 使用 LayoutManager。不确定为什么要使用绝对定位,但这是它引起的问题的完美示例。
FlowLayout 具有简单的居中功能,许多其他布局管理器也支持居中。
I strongly suggesting using a LayoutManager for your GUI. Not sure why you are using absolute positioning, but this is a perfect example of the problems it causes.
FlowLayout
has a simple centering ability and many other layout manager support centering as well.