8

I am not clear about what is the difference between setSize() and setPreferredSize(). what would happen if i use setSize() instead of setPreferredSize().


And what exactly does pack() method do ?

musiKk
  • 14,751
  • 4
  • 55
  • 82
program-o-steve
  • 2,630
  • 15
  • 48
  • 67
  • 6
    See [this post](http://stackoverflow.com/questions/1783793/java-difference-between-the-setpreferredsize-and-setsize-methods-in-componen) – THelper Jun 17 '11 at 10:56
  • 3
    The answer is related to what layout manager you are using. Some don't care about `setSize()` – Kaj Jun 17 '11 at 10:56

1 Answers1

18

Calling pack() on a window will size it based on the preferredSize of its containing components. It will be as small as possible but taking into account the preferredSize and layout of its components. If you just randomly use frame.setSize(), then the components added to the content pane will expand/contract to fit the space available, which means the preferred size of each component may be overridden.

setSize() sets the size of the component and 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 ...

See Java: Difference between the setPreferredSize() and setSize() methods in components

Community
  • 1
  • 1
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328