Java Reference
In-Depth Information
Another common layout called
GridLayout
lays out components in a grid of rows
and columns. You construct a
GridLayout
by passing it the number of rows and the
number of columns. When you add components to the frame, they are laid out in
equal-sized rectangles. The components are placed in the rectangles in row-major
order (left to right, top to bottom). We'll use only buttons in this example, so that you
can clearly see each component's size and shape:
// 2 rows, 3 columns
frame.setLayout(new GridLayout(2, 3));
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
This code produces the graphical output that follows. As resizing the window
demonstrates,
GridLayout
forces every component to be the same size, even though
that can result in awkward stretching of the components.
The third and final layout manager that we'll discuss in this section is called
BorderLayout
. A
BorderLayout
divides the frame into five sections: north, south,
west, east, and center. When you use a
BorderLayout
to add components to a frame,
you pass two parameters: the component to add and a constant representing the
region in which to place it. The constants are called
BorderLayout.NORTH
,
BorderLayout.SOUTH
,
BorderLayout.WEST
,
BorderLayout.EAST
, and
BorderLayout.CENTER
. If you do not pass a second parameter representing the
region, Java will place the component in the center.
The following program demonstrates the addition of several buttons to a
BorderLayout
:
1 // Lays out several components using a BorderLayout.
2
3
import
java.awt.*;
4
import
javax.swing.*;
5
Search WWH ::
Custom Search