The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)

 <  Day Day Up  >  

Here's a snapshot of an application that uses a GridLayout . [19]

[19] GridLayout API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GridLayout.html.

Figure 23. A simple GUI that uses GridLayout .

You can run GridLayoutDemo using Java Web Start or compile and run the example yourself. [20]

[20] To run GridLayoutDemo using Java Web Start, click the GridLayoutDemo link on the RunExamples/layout.html page on the CD. You can find the source files here: JavaTutorial/uiswing/layout/example-1dot4/index.html#GridLayoutDemo .

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

Here's the code that creates the GridLayout object 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

Table 10 lists the constructors available in the GridLayout API. You can find the relevant API documentation online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GridLayout.html.

Table 10. GridLayout Constructors

Constructor

Purpose

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

Create a GridLayout instance. At least one of the rows and columns arguments must be nonzero; rows has precedence over columns . 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 GridLayout examples.

Example

Where Described

Notes

GridLayoutDemo

This section

Uses a 2-column grid.

ComboBoxDemo2

How to Use Combo Boxes (page 176)

Uses a 1- x -1 grid to make a component as large as possible.

LabelDemo

How to Use Labels (page 253)

Uses a 3-row grid.

DragPictureDemo

How to Use Drag and Drop and Data Transfer (page 545)

Uses a 4-row grid to present 12 components that display photographs.

 <  Day Day Up  >  

Категории