Java Reference
In-Depth Information
add( )
method has several versions. The general form of the one used by the program is
shown here:
Component add(Component
comp
)
By default, the content pane associated with a
JFrame
uses a border layout. This version
of
add( )
adds the component (in this case, a label) to the center location. Other versions of
add( )
enable you to specify one of the border regions. When a component is added to the
center, its size is automatically adjusted to fit the size of the center.
The last statement in the
SwingDemo
constructor causes the window to become visible.
Ask the Expert
Q
:
I have seen Swing programs that use a method called
getContentPane( )
when
adding a component to the content pane. What is this method and do I need to
use it?
A
:
This question brings up an important historical point. Prior to JDK 5, when adding a
component to the content pane, you could not invoke the
add( )
method directly on a
JFrame
instance. Instead, you needed to explicitly call
add( )
on the content pane of
the
JFrame
object. The content pane can be obtained by calling
getContentPane( )
on a
JFrame
instance. The
getContentPane( )
method is shown here:
Container getContentPane( )
It returns a
Container
reference to the content pane. The
add( )
method was then called
on that reference to add a component to a content pane. Thus, in the past, you had to use
the following statement to add
jlab
to
jfrm
:
Here,
getContentPane( )
first obtains a reference to the content pane, and then
add( )
adds the component to the container linked to this pane. This same procedure was also re-
quired to invoke
remove( )
to remove a component and
setLayout( )
to set the layout
manager for the content pane. You will see explicit calls to
getContentPane( )
frequently