• How to use Grid Layout in Java

    We tackled about Flow Layout and Border Layout from our previous post. Next in line is the Grid Layout in Java. Grid Layout placed its components by order of how it was added. First, the frame or the container that was set to grid layout will be sliced into equal sizes of cells, of row and columns. The first component that was added will then take the first cell, the second component to the second cell and so on. The construction of Grid Layout is this:

    GridLayout(int rows, int columns);

    Using Grid Layout in Java Example

    package com.javapointers.javase;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
     * @author javapointers
    public class GridLayoutTest {
        JFrame frame;
        public GridLayoutTest() {
            frame = new JFrame("GridLayout Test");
            frame.setSize(500, 400);
            //create new instance for gridlayout with 2 rows and 3 columns
            GridLayout layout = new GridLayout(2, 3);
            frame.add(new JButton("Button 1"));
            frame.add(new JButton("Button 2"));
            frame.add(new JButton("Button 3"));
            frame.add(new JButton("Button 4"));
            frame.add(new JButton("Button 5"));
            frame.add(new JButton("Button 6"));
        public static void main(String args[]) {
            GridLayoutTest test = new GridLayoutTest();

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

    grid layout example

    Next tutorial will be about how to use Card Layout in Java.

    Related Post