# What are the differences between GridLayout and GridBagLayout in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells with each component occupying one or more cells called Component display area.

## GridLayout

A GridLayout arranges the components in a rectangular grid. It arranges component in the cells and each cell has the same size. Components are placed in columns and rows. GridLayout(int rows, int columns) takes two parameters that are a column and a row.

## Example

import java.awt.*;
import javax.swing.*;
public class GridLayoutTest{
GridLayoutTest() {
JFrame frame = new JFrame("GridLayout Test");
JButton button1, button2, button3, button4;
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
frame.setLayout(new GridLayout(2,2));
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutTest();
}
}

## GridBagLayout

A GridBagLayout extends the capabilities of the GridLayout. GridBagLayout places component in each individual cell in a grid and also allows the component to span to multiple columns or rows. In order to use GridBagLayout, we need to create a GridBagConstraints object and fill appropriate properties.

## Example

import javax.swing.*;
import java.awt.*;
public class GridBagLayoutTest extends JFrame {
public GridBagLayoutTest() {
setTitle("GridBagLayout Test");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 5;
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridx = 2;
gbc.gridy = 4;
}