How to use GridBag Layout in Java

We already discussed Flow Layout, Border Layout, Grid Layout, Card Layout and this will be our last layout manager that we will be discussing. Using GridBag Layout in Java is one of the complex layout manager but very powerful.

A Grid Bag Constraint should be defined to layout the components properly.

package com.javapointers.javase;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GridBagLayoutTest {

    JFrame frame;
    JButton button1, button2;
    JPanel panel;
    GridBagLayout gbl;
    GridBagConstraints gbc;

    public GridBagLayoutTest() {
        frame = new JFrame("GridBagLayout Test");
        frame.setSize(500, 400);
        button1 = new JButton("Button 1");
        button2 = new JButton("Button 2");
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(200,300));

        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();


        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.BOTH;
        frame.add(button1, gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.gridheight = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.BOTH;
        frame.add(button2, gbc);

        gbc.gridx = 3;
        gbc.gridy = 0;
        gbc.gridheight = 4;
        gbc.gridwidth = 4;
        gbc.fill = GridBagConstraints.BOTH;
        frame.add(panel, gbc);


    public static void main(String args[]) {
        GridBagLayoutTest test = new GridBagLayoutTest();

When we run  our program, the UI will be like this:

In our above example, we have defined GridBagLayout as gbl and GridBagConstraints as gbc. GridBagConstraints define how our components will be layout in our container. Some constraints are:

  • gbc.gridx = 0;

    means that layout the component starting from 0 in x-coordinate.

  • gbc.gridy = 0;

    means that layout the component starting from 0 in y-coordinate.

  • gbc.gridheight = 1;

    means that this component will allocate 1 cell in height.

  • gbc.gridwidth = 1;

    means that this component will allocate 1 cell in width.

  • gbc.fill = GridBagConstraints.BOTH;

    means to fill all the cells horizontally and vertically.

  • frame.add(button1, gbc);

    add the component with the constraints that we defined.

And that’s how to use GridBag Layout in Java. It is kinda complex but still powerful with the use of GridBagConstraints class. The next tutorial is about JLabel, JTextField and JPasswordField.

Share this tutorial!