Simina Alin
Simina Alin

Reputation: 133

How do I use JFrame.pack()?

How I can use pack() and what is it doing?

For example:

//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//4. Size the frame.  (How does pack() set the frame size???)
frame.pack();

//5. Show it.
frame.setVisible(true);

Upvotes: 0

Views: 2300

Answers (2)

Luke Willis
Luke Willis

Reputation: 8580

pack changes the size of your JFrame to the smallest possible size that will still hold all the elements you've put in it.

Upvotes: 0

aioobe
aioobe

Reputation: 421140

The behaviour of the method is specified in the documentation (the javadoc).

Here's the documentation for Window.pack.

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

Upvotes: 3

Related Questions