Difference between setSize() and setPreferredSize() in Java
The difference between setSize() and setPreferredSize() is a bit complicated. Sometimes we use setSize() and sometimes setPreferredSize(). Sometimes one meets our needs and the other doesn't, so what's the... The main difference between these two methods? Which one should we use for JFrame and JPanel?The answer is if your component doesn't have a parent, use setSize() which changes the size of a component otherwise use setPreferredSize() and both methods setMinimumSize() and setMaximumSize(). setPreferredSize() chooses the ideal size for a component, the layoutmanager will try to arrange the right space for your component.
setSize() does nothing if the parent component uses a layout manager, the place where setSize() has an effect would be in top-level components like JFrame and JWindow. You need to call: setSize() If you have components inside the parent without a layout manager.
So, setPreferredSize() You have to do the right thing if you have a layout manager because most of them work in recovering the optimal, minimum and maximum size of their components. Use setSize() and setLocation to position these components according to the parameters of the chosen layout.
Example:
A BorderLayout will try to set the bounds of the northern region equal to the dimension specified in setPreferredSize() of its northern region. It may end up larger than that depending on the size of JFrame and the size of the size of other components according to layout.
As conclusion:
- setPreferredSize() calculates the optimal location and dimension of the component if you have a layout.
- If you don't have a layout, that's setSize() that is used.