Container
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,
JFrame,
and JDialog.
These are never held inside other containers.
JApplet
extends the Applet
class as shown by this diagram:
java.lang.Object
|
+--java.awt.Component
|
+--java.awt.Container
|
+--java.awt.Panel
|
+--java.applet.Applet
|
+--javax.swing.JApplet
The following example illustrates the essentials of creating an
instance of JApplet:
|
SwingButtonApplet.java |
import
javax.swing.*;
import java.awt.*;
/**
Simple demo of adding a JComponent subclass, here a
* JButton, to the content pane. **/
public class
SwingButtonApplet extends JApplet
{
public void init
() {
// Swing adds JComponents to the containers
// "content pane" rather than
directly to the panel
// as with the AWT.
Container
content_pane = getContentPane
();
// Create an instance of JButton
JButton
button = new JButton ("A
Button");
// Add the button to the contentPane.
content_pane.add(button);
}
} //
SwingButtonApplet
|
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
instance.
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
Tutorial)
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(),
remove(),
and setLayout()
methods so that they forward all calls to the content pane automatically
for the JFrame,
JDialog,
JWindow,
JApplet
and JInternalFrame
components.
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
|