尺寸,仅更改宽度/高度
如何仅更改需要 Dimension 对象的组件的宽度或高度?目前我是这样做的:
jbutton.setPreferredSize(new Dimension(button.getPreferredSize().width, 100));
但我有一种感觉,我做错了。 如果有更好的方法,解决这个问题的最佳方法是什么?
How do I only change the width or height of a component that requires a Dimension
object? Currently I do it like this:
jbutton.setPreferredSize(new Dimension(button.getPreferredSize().width, 100));
But I have a feeling that I'm doing it the wrong way.
What is the best way to approach this if there is a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有同样的问题,但使用不同的应用程序 - 我只需要限制我添加到带有 BoxLayout 的容器中的 JPanel 的高度。因此,当我对其调用setMaximumSize并使用其PreferredSize作为宽度时,结果是它在水平维度上没有得到我期望的拉伸;它变得更短,因为这是它的首选尺寸。我找不到布局管理器应用的实际宽度,因此不知道在新维度中使用什么宽度,但我想要的高度设置效果很好。最终的答案是:
然后 BoxLayout 管理器为 myJpanel 提供了仍然水平填充容器的正确下部宽度,以及我想要防止垂直拉伸的下部高度。
I had the same question but with a different application - I needed to limit the height only, of a JPanel I was adding to a container with a BoxLayout. So when I called setMaximumSize on it and used its PreferredSize for the width, the result was that it did not get the stretching that I expected in the horizontal dimension; it came out shorter because that was its preferred size. I couldn't find what actual width the layout manager was applying, so was at a loss as to what width to use in the new Dimension but the setting I wanted for height worked just fine. The final answer was:
Then the BoxLayout manager gave myJpanel the correct lower width that still filled the container horizontally, and the lower height that I wanted to prevent the vertical stretch.
首先,您没有更改 JButton 的尺寸。您正在指定所需的首选大小,该大小最终可以应用于您的 JButton,具体取决于它所插入的组件的 LayoutManager。
对于 Dimension 对象的使用来说,这很好。最终您可以直接访问 Dimension 字段:
但这几乎是同一件事。
First of all you are not changing the dimension of JButton. You are specifying the desired preferred size, that can be eventually applied to your JButton depending on the LayoutManager of the component it's inserted into.
For what concern the use of Dimension object that's fine. Eventually you can access directly Dimension field:
but that's pretty much the same thing.
我最终按照克利奥帕特拉所说的做了。不改变preferredSize,而是让布局管理器完成这项工作。因为这是更改组件大小的正确方法。
I ended up doing it the way Kleopatra said. Not changing the preferredSize but letting the layout manager do the job. Since this is the proper way to change the size of a component.