站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

How to Use GridLayout - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Laying Out Components Within a Container

How to Use GridLayout

Here's a snapshot of an application that uses a GridLayout (in the API reference documentation).

A snapshot of GridLayoutDemo

You can run GridLayoutDemo using JavaTM Web Start (in the Creating a GUI with JFC/Swing trail). Its code is in GridLayoutDemo.java (in a .java source file).

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 (in a .java source file).

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 (in the Creating a GUI with JFC/Swing trail) How to Use Combo Boxes (in the Creating a GUI with JFC/Swing trail) One of many examples that use a 1x1 grid to make a component as large as possible.
LabelDemo (in the Creating a GUI with JFC/Swing trail) How to Use Labels (in the Creating a GUI with JFC/Swing trail) Uses a 3-row grid.
DragPictureDemo (in the Creating a GUI with JFC/Swing trail) How to Use Drag and Drop and Data Transfer (in the Creating a GUI with JFC/Swing trail) Uses a 4-row grid to present 12 components that display photographs.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.