Swing基础之设置大小

setSize()/setBounds() 和setPreferredSize() 的区别:


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 frame, the size of the other components in the layout, and so on.

意思是:

顶层容器(JFrames and JWindows)和放在JScrollPane 中的组件使用setSize()/setBounds()都会有效果,如果容器的layoutManager 为null,则必须使用setSize().

setPreferredSize(),setMinimumSize(),setMaximumSize() 则被layoutManager 来确定组件的大小.

原文地址:https://www.cnblogs.com/predisw/p/4885627.html