What is the Java GridLayout?

The GridLayout class in Java is used to design layouts that have a specified number of rows and columns in a rectangular grid. Each component is placed in the equal-sized rectangle. The changes are visible for each small-rectangle whenever its size is adjusted.


Constructors

svg viewer

Common methods

Method Description
setColumns(int col) This function sets the specified number of columns for the layout.
setRows(int row) This function sets the specified number of rows for the layout.
setHgaps(int val) This function sets the horizontal gaps according to the specified value.
setVgaps(int val) This function sets the vertical gaps according to the specified value.

Example

import java.awt.*;
import javax.swing.*;
public class GridLayout{
JFrame frm;
MyGridLayout(){
frm=new JFrame();
JButton btn1=new JButton("1");
JButton btn2=new JButton("2");
JButton btn3=new JButton("3");
JButton btn4=new JButton("4");
JButton btn5=new JButton("5");
JButton btn6=new JButton("6");
frm.add(btn1);
frm.add(btn2);
frm.add(btn3);
frm.add(btn4);
frm.add(btn5);
frm.add(btn6);
frm.setLayout(new GridLayout(2,3));//creating grid layout of 2 row and 3 columns
frm.setSize(300,300);
frm.setVisible(true);
}
public static void main(String[] arguments) {
new GridLayout();
}
}

Code output

svg viewer
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved