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 contains in individual tabbed panes (like those pictured in Figure 11-1) but Swing and the AWT also define generic container classes, such as JPanel.

Example 11-1 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 11-1 illustrates the concept of the containment hierarchy of a GUI, using color to represent the nesting depth of the hierarchy. Figure 11-2 shows what the Containers class looks like when displayed with the ShowBean program as follows:

% java je3.gui.ShowBean je3.gui.Containers
Nested containers

Figure 11-2. Nested containers

Example 11-1. Containers.java

package je3.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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.