Java Swing Tutorial - Java Swing GridLayout








A GridLayout arranges components in a grid with equally sized cells. Each component is placed in one cell.

GridLayout does not honor the preferred size of the component. It divides the available space into equally sized cells and resizes each component to the cell's size.

When creating GridLayout we specify either the number of rows or the number of columns in the grid.

We can create a GridLayout using one of the following three constructors of the GridLayout class:

GridLayout()
GridLayout(int rows,   int cols)
GridLayout(int rows,   int cols, int hgap,   int  vgap)

We can specify the number of rows, the number of columns, a horizontal gap, and a vertical gap between two cells in the grid from constructors. These properties can also be set using the methods setRows(), setColumns(), setHgap(), and setVgap() respectively.

The no-args constructor creates a grid of one row. The number of columns is the same as the number of components added to the container.

The following code creates a grid layout of one row.

GridLayout gridLayout  = new GridLayout();

The following code creates a grid layout of 5 rows. It use 0 as the number of columns. The number of columns will be computed.

GridLayout gridLayout  = new GridLayout(5, 0);

The following code creates a grid layout of 3 columns. It uses 0 as the number of rows. The number of rows will be computed.

GridLayout gridLayout  = new GridLayout(0, 3);

The following code creates a grid layout with 2 rows and 3 columns.

GridLayout gridLayout  = new GridLayout(2, 3);

The following code creates a GridLayout of three rows with a horizontal gap of 10 pixels and a vertical gap of 20 pixels between cells.

GridLayout gridLayout  = new GridLayout(3, 0,  10,   20);
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
/*ww  w  . j a v  a2 s  .co m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("GridLayout");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(3, 0));

    for (int i = 1; i <= 9; i++) {
      buttonPanel.add(new JButton("Button  " + i));
    }

    contentPane.add(buttonPanel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}