What is the difference between pack() and setSize() in java swing ?

This tutorial explains a difference between the pack() method and setSize method. pack() method sets the frame size such that all the components inside it are layed out and fits well inside the frame.
Basically pack() is Windows method which sets the Window size as per layout and size of the subcomponents. In short size is calculated as per need of size of subcomponents and its layout properites.If window or frame or its owner is not displayable, both are made displayable even before calculating its preferred size. Once the preferred size is calculated, the window will be validated.
In contrast to the pack method, setSize method takes arguments in form such as dimentions or width and height etc. And these arguments decides the size of a frame or window.

Following program demonstrates the difference between the pack and size method, using pack method the size is as needed for the buttons and setSize method sets the size as per specified height and width.

    private Button b1 = new Button(  "Pack" );
    private Button b2 = new Button( "Vs" );
    private Button b3 = new Button( "SetSize");
    private Button b4 = new Button( "Example" );

    public PackVsSetSize() {
        super( "pack() vs. setSize()" );
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing( WindowEvent e) {

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

        testPane.add( b1 );
        testPane.add( b2 );
        testPane.add( b3 );
        testPane.add( b4 );

        //b1.setEnabled( false );
        //this.setSize( 400, 90 ); //Setting the size using setSize method with height and weight

        b3.setEnabled( false );


Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment