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
The short answer is: it's complicated.
The slightly longer answer is: use
setSize()
if your component's parent has no layout manager, andsetPreferredSize()
and its relatedsetMinimumSize
andsetMaximumSize
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
andJWindows
) and things that are inside ofscrolled panes
. You also must callsetSize()
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 usingsetSize()
andsetLocation()
to position those components according to the layout's rules. So (as an example) aBorderLayout
will try to make the bounds of its "north" region equal to thepreferred size
of its north component - they may end up larger or smaller than that, depending on the size of thejframe
, the size of the other components in the layout, and so on.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 ...
setSize()
orsetBounds()
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 likesetPreferredSize()
andsetMinimumSize()
etc.And be sure that the component's container uses a layout manager that respects the requested size. The
FlowLayout
,GridBagLayout
, andSpringLayout
managers use the component's preferred size (the latter two depending on the constraints you set), butBorderLayout
andGridLayout
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.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.