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

AWTJavaObject Oriented ProgrammingProgrammingSwing

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++) {
}