Trail: Creating a GUI with JFC/Swing
Lesson: Laying Out Components Within a Container
How to Use GridLayout
How to Use GridLayout
Here's a snapshot of an application that uses a GridLayout.

A snapshot of GridLayoutDemo

You can run GridLayoutDemo using JavaTM Web Start. Its code is in GridLayoutDemo.java.

A GridLayout places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize the GridLayoutDemo window, you'll see that the GridLayout changes the cell size so that the cells are as large as possible, given the space available to the container.

Below is the code that creates the GridLayout and the components it manages. You can find the whole program in GridLayoutDemo.java.

pane.setLayout(new GridLayout(0,2));

pane.add(new JButton("Button 1"));
pane.add(new JButton("Button 2"));
pane.add(new JButton("Button 3"));
pane.add(new JButton("Long-Named Button 4"));
pane.add(new JButton("5"));
The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary.

The GridLayout API

[PENDING: This section will be converted to present its information in an API table.]

The GridLayout class has two constructors:

public GridLayout(int rows, int columns)
public GridLayout(int rows, int columns,
                  int horizontalGap, int verticalGap)
At least one of the rows and columns arguments must be nonzero; the rows argument has precedence over the columns argument. The horizontalGap and verticalGap arguments to the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero.

Examples that Use GridLayout

The following table lists some of the examples that use grid layout.

Example Where Described Notes
GridLayoutDemo This page Uses a 2-column grid.
ComboBoxDemo2 How to Use Combo Boxes One of many examples that use a 1x1 grid to make a component as large as possible.
LabelDemo How to Use Labels Uses a 3-row grid.
DragPictureDemo How to Use Drag and Drop and Data Transfer Uses a 4-row grid to present 12 components that display photographs.

Previous page: How to Use GridBagLayout
Next page: How to Use SpringLayout