swing Layout management Grid layout


Example

The GridLayout allows you to arrange components in the form of a grid.

You pass the number of rows and columns you want the grid to have to the GridLayout's constructor, for example new GridLayout(3, 2) will create a GridLayout with 3 rows and 2 columns.

When adding components to a container with the GridLayout, the components will be added row by row, from left to right:

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

public class Example {
    public static void main(String[] args){
        SwingUtilities.invokeLater(Example::createAndShowJFrame);
    }

    private static void createAndShowJFrame(){
        JFrame jFrame = new JFrame("Grid Layout Example");

        // Create layout and add buttons to show restraints
        JPanel jPanel = new JPanel(new GridLayout(2, 2));
        jPanel.add(new JButton("x=0, y=0"));
        jPanel.add(new JButton("x=1, y=0"));
        jPanel.add(new JButton("x=0, y=1"));
        jPanel.add(new JButton("x=1, y-1"));

        jFrame.setContentPane(jPanel);
        jFrame.pack();
        jFrame.setLocationRelativeTo(null);
        jFrame.setVisible(true);
    }
}

This creates and shows a JFrame that looks like:

enter image description here

A more detailed description is available: GridLayout