GridLayout – Java Swing – Example
In this tutorial, we are going to see an example of GridLayout in Java Swing. GridLayout is used to arrange the components in a rectangular grid. One component is displayed in each rectangle.

GridLayout constructors class are :
| GridLayout() | Creates a grid layout with one column per component in a row. |
| GridLayout(int rows, int columns) | Creates a grid layout with the specified rows and columns but without spaces between the components. |
| GridLayout(int rows, int columns, int hgap, int vgap) | Creates a grid layout with the specified rows, columns and the given horizontal, vertical spaces. |
Example of GridLayout in Java Swing:
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
MyGridLayout()
{
JFrame frame = new JFrame();
JButton btn1 = new JButton("A");
JButton btn2 = new JButton("B");
JButton btn3 = new JButton("C");
JButton btn4 = new JButton("D");
JButton btn5 = new JButton("E");
JButton btn6 = new JButton("F");
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);
//set the grid layout of 3 rows and 2 columns
frame.setLayout(new GridLayout(3,2));
frame.setSize(300,300);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output:





