5.3.1 Adding a GUI Component to a Container
Before a basic GUI component can appear on-screen, it must first be
added to a Container
via the add
method.
A Container
is a special kind of component: its sole
purpose is to group components in a specified arrangement. You can
think of a window, applet, or a panel to hold components.
The arrangement of components inside a container is
determined by the container's layout. We shall discuss this later.
The add
method of a container can be called
in two ways:
add(Component component)
add(String position, Component component)
The first way of adding components to a container works in all cases.
The two-argument call is only useful for particular layouts. For example,
in the BorderLayout
you can use the keywords
"North"
, "South"
, "East"
,
"West"
, and "Center"
to specify the location
where a component should be placed.
There is one complication to adding components to a container: will the
corresponding Peer
object, that controls the object's
look and feel, be created or not. Without the peer, the object will not
be shown or changes in the object's properties are not acknowledged.
Peers are created only just before their corresponding component
object is drawn for the first time. When you add a component to a
non-visible container (a container with no peer), then just before
the container is shown for the first time, its peer and the peers of
all components it contains are created. No problem. But what happens when
you add a component to a visible container? In this case you explicitly have
to create a peer for each object that you add. You do
this by calling the validate
method. This method is usually
invoked on a Container
class instead of invoked on individual
components because validating a container will also validate the
components contained in it. For example, after you add components
to an Applet
object, you call validate()
on the
Applet.