Java Reference
In-Depth Information
Containers
The second step in creating a GUI is to place the components you have created
and configured into appropriate containers. Chapter 2 of
Java Foundation Classes
in a Nutshell
contains tables that list the container classes available in the AWT and
Swing packages. Many of these container classes have specialized uses.
JFrame
is a
top-level window, for example, and
JTabbedPane
displays the components it con-
tains in individual tabbed panes. Example 10-1 demonstrated the use of these con-
tainers. But Swing and the AWT also define generic container classes, such as
JPanel
.
Example 10-2 is a listing of
Containers.java
. This class is a subclass of
JPanel
. Its
constructor method creates a number of other nested
JPanel
instances, as well as
a number of
JButton
objects contained by those
JPanel
classes. Example 10-2
illustrates the concept of the containment hierarchy of a GUI, using color to repre-
sent the nesting depth of the hierarchy. Figure 10-2 shows what the
Containers
class looks like when displayed with the
ShowComponent
program as follows
(another single long command-line that has been wrapped onto two lines):
% java com.davidflanagan.examples.gui.ShowComponent \
com.davidflanagan.examples.gui.Containers
For variety, Figure 10-2 uses the Motif look-and-feel and shows the contents of the
Look and Feel menu.
Figur e 10•2. Nested containers
Example 10•2: Containers.java
package com.davidflanagan.examples.gui;
import javax.swing.*;
import java.awt.*;
/**
* A component subclass that demonstrates nested containers and components.
* It creates the hierarchy shown below, and uses different colors to
* distinguish the different nesting levels of the containers
*
*
containers---panel1----button1
*
|
|---panel2----button2
*
|
|
|----panel3----button3
*
|
|------panel4----button4
*
|
|----button5
*
|---button6