What is GridLayout - Java Swing

Java examples for Swing:GridLayout

Introduction

A GridLayout lays out components in a grid of equally sized cells.

Each component is placed in one cell.

GridLayout does not respect the preferred size of the component.

GridLayout divides the available space into equally sized cells and resizes each component to the cell's size.

We can specify either the number of rows or the number of columns in the grid.

You 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)

Create a grid layout of one row

import java.awt.GridLayout;

public class Main {
  public static void main(String[] argv) throws Exception {
    GridLayout gridLayout = new GridLayout();
  }
}

The second constructor creates a GridLayout by a specified number of rows or columns.

Create a grid layout of 5 rows. Specify 0 as the number of columns. The number of columns will be computed.

import java.awt.GridLayout;

public class Main {
  public static void main(String[] argv) throws Exception {
    GridLayout gridLayout = new GridLayout(5, 0);
  }
}

Create a grid layout of 3 columns. Specify 0 as the number of rows. The number of rows will be computed.

import java.awt.GridLayout;

public class Main {
  public static void main(String[] argv) throws Exception {
    GridLayout gridLayout = new GridLayout(0, 3);
  }
}

Create a grid layout with 2 rows and 3 columns.

You have specified a non-zero value for rows, so the value for columns will be ignored. It will be computed based on the number of components.

import java.awt.GridLayout;

public class Main {
  public static void main(String[] argv) throws Exception {
    GridLayout gridLayout = new GridLayout(2, 3);
  }
}

You can create a GridLayout of three rows with a horizontal gap of 10 pixels and a vertical gap of 20 pixels between cells, as shown:

import java.awt.GridLayout;

public class Main {
  public static void main(String[] argv) throws Exception {
    GridLayout gridLayout = new GridLayout(3, 0, 10, 20);
  }
}

Related Tutorials