java 尺寸,只改变宽度/高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7177622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dimension, Only changing the width/height
提问by Patrick
How do I only change the width or height of a component that requires a Dimension
object? Currently I do it like this:
如何仅更改需要Dimension
对象的组件的宽度或高度?目前我这样做:
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?
但我有一种感觉,我做错了。如果有更好的方法,最好的方法是什么?
采纳答案by Patrick
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.
我最终按照克利奥帕特拉所说的方式去做了。不改变 preferredSize 而是让布局管理器完成这项工作。因为这是更改组件大小的正确方法。
回答by Heisenbug
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.
首先,您没有更改 JButton 的尺寸。您正在指定所需的首选大小,它最终可以应用于您的 JButton,具体取决于它插入的组件的 LayoutManager。
For what concern the use of Dimension object that's fine. Eventually you can access directly Dimension field:
对于什么问题,使用 Dimension 对象就好了。最终您可以直接访问 Dimension 字段:
Dimension d = button.getPreferredSize();
d.height = 10;
jbutton.setPreferredSize(d);
but that's pretty much the same thing.
但这几乎是一样的。
回答by selofain
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:
我有同样的问题,但使用不同的应用程序 - 我只需要限制我添加到具有 BoxLayout 的容器的 JPanel 的高度。所以当我在它上面调用 setMaximumSize 并使用它的 PreferredSize 作为宽度时,结果是它没有得到我期望的水平尺寸的拉伸;它的尺寸更短,因为这是它的首选尺寸。我找不到布局管理器应用的实际宽度,因此不知道在新 Dimension 中使用什么宽度,但我想要的高度设置工作得很好。最后的答案是:
myJPanel.setMaximumSize(new Dimension(<some overly high width value>, <desired height>));
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.
然后 BoxLayout 管理器给 myJpanel 正确的较低宽度仍然水平填充容器,以及我想要防止垂直拉伸的较低高度。