Java Swing:如何为组件定义一个最小维度(两个维度中的一个)?
要成功定义最小尺寸,我必须执行以下操作:
// setting minimal width AND height
Dimension min = new Dimension(100, 100);
comp.setMinimumSize(min);
comp.setPreferredSize(min);
comp.setSize(min);
当我留下一行时,它不起作用,这很奇怪,但这不是重点。
我该如何限制两个尺寸(宽度或高度)中的一个,并让组件和/或布局管理器自动决定未指定强>维度?
当我为不想限制的尺寸使用非常小的值时,许多组件显示错误(即太小)。
To define minimal size successfully, I have to do the following:
// setting minimal width AND height
Dimension min = new Dimension(100, 100);
comp.setMinimumSize(min);
comp.setPreferredSize(min);
comp.setSize(min);
When I left one line out it doesn't work, which is strange, but it's not the point.
What do I do to limit just one of two dimensions (width or height) and let the component and/or the layout manager decide automatically about the unspecified dimension?
When I use a very small value for that dimension which I don't want to limit, many components are displayed wrong (i.e. too small).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下(即,如果未在组件上调用
setMinimumSize
),getMinimumSize
委托给组件的布局管理器,因此您可以尝试重新定义getMinimumSize
> 方法如下:如果您这样做,请记住您不应在组件上调用
setMinimumSize
。By default (i.e. if
setMinimumSize
has not been called on the component)getMinimumSize
delegates to the component's layout manager, so you can try to redefine thegetMinimumSize
method as follows:If you do this, remember that you should not call
setMinimumSize
on the component.我自己提出了一种方法:
对于将所有内容对齐一个轴的布局管理器(例如 BoxLayout),可以将“未定义的维度”设置为 Integer.MAX。这很奇怪,但它确实有效。似乎与对齐轴相反的轴被忽略(除非它太小,如问题中提到的)。
如前所述,可与轴对齐布局管理器一起使用。
是的,Java Swing 还有另一个谜团......
I propose an approach by myself:
For layout managers which align everything one axis (such as
BoxLayout
), one can specify "undefined dimension" set toInteger.MAX
. It is strange, but it works. It seems that the axis which is opposite to the alignment axis is ignored (unless it's too small, as mentioned in the question).Works, as mentioned, with axis-aligning layout managers.
Yes, there goes another mystery of Java Swing...