Java Reference
In-Depth Information
Swing containers -
JFrame
,
JApplet
,
JDialog
,
JWindow
- are conceptually
constructed of several such overlapping
panes
. The panes organize the display
of the components, the interception of events, the 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 the panes system. However, for most GUI building
you only need to deal with the content pane.
We note that 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. We con-
tinue to use the content pane explicitly in this topic for those readers who have
not yet upgraded their Java environment to the 5.0 platform.
6.5.1
JPanel
and
JButton
We typically build an interface with one or more instances of
JPanel
.A
JPanel
is a container that holds other components. The following applet creates a subclass
of
JPanel
called
ActionButtonsPanel
that holds two
JButton
objects. An
instance of this
JPanel
is then added to the applet's content pane. Figure 6.3
shows the resulting display.
import java.awt.*;
import javax.swing.*;
/** Demonstrate the Creation of a JPanel subclass. **/
public class
ButtonsPanelApplet
extends JApplet
{
public void init () {
Container content
-
pane = getContentPane ();
// First create a panel of buttons
ActionButtonsPanel buttons
-
panel =
new ActionButtonsPanel ();
content
-
pane.add (buttons
-
panel);
}
}
// class ButtonsPanelApplet
// JPanel subclass with two buttons
class
ActionButtonsPanel
extends JPanel
{
Figure 6.3
The
program
Buttons-
PanelApplet
puts
two
JButton
components on a
JPanel
.
ActionButtonsPanel ()
{
// Create two buttons
Search WWH ::
Custom Search