When can we use the pack() method in Java?


The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods. In general, using the pack() method is preferable to call than setSize() method, since pack leaves the frame layout manager in charge of the frame size and layout managers are good at adjusting to platform dependencies and other factors that affect the component size.

Syntax

public void pack()

Example

import java.awt.*;
import javax.swing.*;
public class PackMethodTest extends JFrame {
   public PackMethodTest() {
      setTitle("Pack() method Test");
      setLayout(new FlowLayout());
      setButton();
      pack(); // calling the pack() method
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   void setButton() {
      for(int i=1; i < 6; i++) {
         add(new JButton("Button" +i));
      }
   }
   public static void main(String args[]) {
      new PackMethodTest();
   }
}

Output

Updated on: 03-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements