GridLayout

GridLayout arranges components into regularly spaced rows and columns. The components are arbitrarily resized to fit the grid; their minimum and preferred sizes are consequently ignored. GridLayout is most useful for arranging identically sized objects—perhaps a set of JPanels, each using a different layout manager.

GridLayout takes the number of rows and columns in its constructor. If you subsequently give it too many objects to manage, it adds extra columns to make the objects fit. You can also set the number of rows or columns to zero, which means that you don’t care how many elements the layout manager packs in that dimension. For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of columns; if you put ten components into this layout, you’ll get two rows of five columns each.[45]

The following example sets a GridLayout with three rows and two columns as its layout manager; the results are shown in Figure 16.3.

//file: Grid.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Grid extends JPanel {

  public Grid( ) {
    setLayout(new GridLayout(3, 2));
    add(new JButton("One"));
    add(new JButton("Two"));
    add(new JButton("Three"));
    add(new JButton("Four"));
    add(new JButton("Five"));
  }

  public static void main(String[] args) {
    JFrame f = new JFrame("Grid");
    f.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(200, 200);
    f.setLocation(200, 200);
    f.setContentPane(new Grid( ));
    f.setVisible(true);
  }
}
A grid layout

Figure 16-3. A grid layout

The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.



[45] Calling new GridLayout(0, 0)causes a runtime exception; either the rows or columns parameter must be greater than zero.

Get Learning Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.