What is the main difference between setSize()
and setPreferredSize()
. Sometimes I used setSize()
, sometimes setPreferredSize()
, sometimes one does what I want, sometimes the other.
What call should I use for JFrame
s and JPanel
s?
setBounds is used to define the bounding rectangle of a component. This includes it's position and size. The is used in a number of places within the framework. It is used by the layout manager's to define the position and size of a component within it's parent container.
Usage depends on whether the component's parent has a layout manager or not.
setSize()
-- use when a parent layout manager does not exist;setPreferredSize()
(also its related setMinimumSize
and setMaximumSize
) -- use when a parent layout manager exists.The setSize()
method 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 (JFrame
s and JWindow
s) 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.
Generally, setPreferredSize()
will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize()
and setLocation()
to position those components according to the layout's rules.
For example, a BorderLayout
tries 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With