pack() vs. setSize() Method in Java

This section provides you an example which illustrates you about the main difference between the pack() method and the setSize() method of the Java Swing.

pack() vs. setSize() Method in Java

This section provides you an example which illustrates you about the main difference between the pack() method and the setSize() method of the Java Swing.

pack() vs. setSize() Method in Java

pack() vs. setSize() Method in Java

     

This section provides you an example which illustrates you about the main difference between the pack() method and the setSize() method of the Java Swing.

Here, you can see the given example provides a JFrame with some button component like Button 1, Button 2, Button3, Button 4, Button 5 etc. on it. The frame is seen by using the pack() method. If you do not use the pack method frame is not resized and only the title of the frame will bee seen. To show everything on the frame, frame will be resized by the pack() method or the setSize() method of Java Swing.

The main difference between the pack() method and setSize() method of Java Swing is as follows:

pack() method gives sets the frame size as per need while the setSize() method takes two parameter in which one is for the width of the frame and another one is for the height of the frame to represent it.

Here is the code of the program

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Pack extends JFrame {
  private Button button1 = new Button("Button 1");
  private Button button2 = new Button("Button 2");
  private Button button3 = new Button("Button 3");
  private Button button4 = new Button("Button 4");
  private Button button5 = new Button("Button 5");

  public Pack() {
  super("pack() vs. setSize() method Example");
  this.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  System.exit(0);
  }
  });

  Container contentPane = this.getContentPane();
  contentPane.setLayout(new FlowLayout());

  contentPane.add(button1);
  contentPane.add(button2);
  contentPane.add(button3);
  contentPane.add(button4);
  contentPane.add(button5);

  //this.setSize(450, 90);
  this.pack();
  }

  public static void main(String[] args) {
  Pack mainFrame = new Pack();
  mainFrame.setVisible(true);
  }  
}

Download this example.

Output of the above example: