GridBagLayout

This layout is more flexible than the grid layout. This layout allows the components span over multiple rows and columns. This layout also enables us to resize the components by assigning appropriate weights to them.

The following snippet assigns the gridbag layout :

gridbagLayout lay = new GridLayout ();
setLayout (lay );

The data members of a special class named GridConstraints enable us to specify the position, size and other aspects of each component.

GridBagConstraints ( int gridx, int gridy);

gridx : To specify the row position in the upper-left region of the component’s display area.
gridy : To specify the column position in the upper-left region of the component’s display area.

When setConstraints() is called to associate the GridBagConstraints object with the button object, it creates a copy of the constraints object that you pass as the argument, and a reference to the copy is stored in the layout — not a reference to the object that you created.

Program

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

class GridBagLayt extends JFrame {
   
    GridBagLayt()
    {
        setTitle("GridBagLayout");
        GridBagLayout lay = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        setLayout(lay);
        setButton("Button1",0,0,gbc,lay);
        setButton("Button2",1,0,gbc,lay);
        setButton("Button3",1,1,gbc,lay);
        setButton("Button4",1,2,gbc,lay);
        setButton("Button5",2,0,gbc,lay);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(700,200);
        setVisible(true);
    }
    
    void setButton(String name,int y,int x,GridBagConstraints gbc,GridBagLayout lay)
    {
        JButton jb = new JButton(name);
        gbc.gridy = y;
        gbc.gridx = x;
        lay.setConstraints(jb, gbc);
        add(jb);
    }
}

public class Javaapp {
   
    public static void main(String[] args) {
       
        GridBagLayt gb = new GridBagLayt();
    }
}

Leave a Comment