components can, as the name implies, hold other components. The
sub-components can themselves be containers or they can be atomic
components that serve a single purpose such as a label or button.
So-called top level containers include JApplet,
These are never held inside other containers.
extends the Applet
class as shown by this diagram:
The following example illustrates the essentials of creating an
instance of JApplet:
Simple demo of adding a JComponent subclass, here a
* JButton, to the content pane. **/
SwingButtonApplet extends JApplet
public void init
// Swing adds JComponents to the containers
// "content pane" rather than
directly to the panel
// as with the AWT.
content_pane = getContentPane
// Create an instance of JButton
button = new JButton ("A
// Add the button to the contentPane.
The steps to creating a Swing interface are not so different from
the AWT (see Chapter
6: Supplements). Instances of individual components are created
and then added to a container.
One difference, however, is that instead of adding directly to
the applet's Panel
container as in the AWT approach, we instead add to the Content
Pane object belonging to the JApplet
The top-level Swing containers - JFrame, JApplet, JDialog, JWindow
- are conceptually constructed of several such panes:
The pane layers in the Swing frame.
(From the JavaSoft
The panes organize the display of the components, the interception
of events, z-ordering of components, and various other tasks. If
you ever want to build a custom component, it is necessary to understand
the details of all this. However, for most GUI building you only
need to deal with the ContentPane,
to which you add components, including those such as JPanel
that can contain other components.
Note: For J2SE 5.0, calling getContentPane()
is no longer required for Swing components. This was accomplished
by enhancing the add(),
methods so that they forward all calls to the content pane automatically
for the JFrame,
In the above example, you would thus only need to invoke add
(button) to place the button on the applet panel. For many
of our examples we continue to use the content pane explicitly
so that the codes will work with earlier compilers. For the exercises
the student can use the J2SE5.0 approach if desired.
For details on the layered construction of the top level containers,
see these sections of the Sun Java Tutorial:
References and Web Resources
Latest update: Oct.25, 2004