Java Reference
In-Depth Information
Example 10•4: GridLayoutPane.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import javax.swing.*;
public class GridLayoutPane extends JPanel {
public GridLayoutPane() {
// Layout components into a grid three columns wide, with the number
// of rows depending on the number of components. Leave 10 pixels
// of horizontal and vertical space between components
this.setLayout(new GridLayout(0, 3, 10, 10));
// Add some components
for(int i = 1; i <= 12; i++) this.add(new JButton("Button #" + i));
}
}
BorderLayout
The
BorderLayout
layout manager arranges up to five components within a con-
tainer. Four of the components are laid out against specific edges of the container,
and one is placed in the center. When you add a component to a container that is
managed by
BorderLayout
, you must specify where you want the component
placed. You do this with the two-argument version of
add()
, passing one of the
constants
NORTH
,
EAST
,
SOUTH
,
WEST
,or
CENTER
defined by
BorderLayout
as the sec-
ond argument. These constants are called
layout constraints
; you use use them
with code like the following:
this.add(b, BorderLayout.SOUTH);
Remember that
BorderLayout
can lay out only one component in each of these
positions.
BorderLayout
does not honor the preferred sizes of the components it manages.
Components specified laid out
NORTH
or
SOUTH
are made as wide as the container
and retain their preferred height.
EAST
and
WEST
components are made as high as
the container (minus the heights of the top and bottom components, if any) and
retain their preferred width. The
CENTER
component is made as large as whatever
space remains in the center of the container, after the specified number of pixels
of horizontal and vertical space are allocated. You do not have to specify the full
five children. For example, the
BorderLayout
class is often used to place a fixed-
size child (such as a
JToolBar
) against one edge of a container, with a variable-
sized child (such as a
JTextArea
) in whatever space remains in the center.
BorderLayout
is the default layout manager for the content panes of
JFrame
and
JDialog
containers. If you do not explicitly specify a layout manager for these
content panes, they use a
BorderLayout
configured to leave no horizontal or verti-
cal space between components.
Example 10-5 lists a program that arranges five buttons using a
BorderLayout
lay-
out manager; Figure 10-5 shows the resulting output.