How do I arrange the swing component using GridLayout?

This example use the GridLayout to create a four by four grid layout. One each of the grid we place a JTextField component to read user inputs.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class GridLayoutDemo extends JFrame {
    public GridLayoutDemo() {

    private void initializeUI() {

        // Create a four by four GridLayout with 5 pixel horizontal and vertical
        // gap between each row or column.
        GridLayout grid = new GridLayout(4, 4, 5, 5);


        JTextField[][] textFields = new JTextField[4][4];
        for (int i = 0; i < textFields.length; i++) {
            for (int j = 0; j < textFields[i].length; j++) {
                textFields[i][j] = new JTextField(String.valueOf((i + 1) * (j + 1)));
                // Put the text at the center of the JTextField component


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GridLayoutDemo().setVisible(true);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.