GridLayoutTest.java

  1. GridLayout places components in a grid of cells.
  2. Each component takes all the available space within its cell.
  3. Each cell is exactly the same size.
  4. Components are added to the layout from left to right, top to bottom.
  5. new GridLayout(3, 4): three rows and four columns,
  6. Setting the number of rows or columns to be zero, and the layout will grow without bounds in the direction with a zero setting.

The GridLayout class has two constructors:

    public GridLayout(int rows, int columns)
    public GridLayout(int rows, int columns, int horizontalGap, int verticalGap)


GridLayoutTest.java

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class GridLayoutTest {

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridLayout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(3,2));
    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"));
    frame.add(new JButton("Button 7"));
    frame.add(new JButton("Button 8"));
    frame.pack();
    frame.setVisible(true);
  }
}


Maintained by John Loomis, updated Thu Mar 26 15:28:00 2020