Java: Difference between the setPreferredSize() an

2018-12-31 15:43发布

Ok, I read the Java Documentation and I just can't figure out what is the main difference between those two methods. Sometimes I used setSize(), sometimes setPreferredSize(), sometimes one does what I want, sometimes the other.

So, what is the main difference between the two? Which one should I use for JFrames and JPanels?

Thanks

4条回答
不流泪的眼
2楼-- · 2018-12-31 16:06

The short answer is: it's complicated.

The slightly longer answer is: use setSize() if your component's parent has no layout manager, and setPreferredSize() and its related setMinimumSize and setMaximumSize if it does.

setSize() probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

As a general rule, setPreferredSize() should do the "right thing" if you've got a layout manager; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, and then using setSize() and setLocation() to position those components according to the layout's rules. So (as an example) a BorderLayout will try to make the bounds of its "north" region equal to the preferred size of its north component - they may end up larger or smaller than that, depending on the size of the jframe, the size of the other components in the layout, and so on.

查看更多
高级女魔头
3楼-- · 2018-12-31 16:11

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

查看更多
不再属于我。
4楼-- · 2018-12-31 16:27

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

查看更多
柔情千种
5楼-- · 2018-12-31 16:28

setSize will resize the component to the specified size.

setPreferredSize sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.

查看更多
登录 后发表回答