Difference between setPrefferedSize and setSize in JPanel

asukai
asukai used Ask the Experts™
on
Can anyone please tell me the difference between setPrefferedSize and setSize in JPanel? When is the appropriate time to use them?

Thanx,

asukai
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hi asukai,

It depends on the layout manager you use. Layout managers decide what size a component will be, not the component itself. The component just informs the layout manager what size it would "like" to be via the preferredSize property.
You can also specify a maximumSize and minimumSize property. A layout manager should then ensure that your component will never be larger than maximumSize and never be smaller than minimumSize.

As far as I know, setSize() is only appropriate when you're using a NullLayout. In this case, setSize() will resize the component to the specified size.
Java Developer
Top Expert 2010
Commented:
setSize() sets the actual size of the component, though if a layout manager is present then it may subsequently change the size.
setPreferredSize() specifies a preferred component size, which may (or may not) be taken into consideration by the layout manager when it lays out your component.
Mick BarryJava Developer
Top Expert 2010

Commented:

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial