Java Reference
In-Depth Information
Using Containers
A container is any component with the
Container
class as a base; so all the Swing components are
containers. The
Container
class is the direct base class for the
Window
class and it provides the ability
to contain other components. Since the
Container
class is an
abstract
class, you cannot create
instances of
Container
. Instead it is objects of the subclasses such as
Window
,
JFrame
, or
JDialog
that inherit the ability to contain other components.
Note that a container cannot contain an object of the class
Window
, or an object of
any of the classes derived from
Window
. An object of any other class that is derived
from
Component
can be contained.
The components within a container are displayed within the area occupied by the container on the
display screen. A dialog box, for example, might contain a
JList
object offering some choices:
JCheckbox
objects offering other options and
JButton
objects representing buttons enabling the user
to end the dialog or enter the selections - all these components would appear within the boundaries of
the dialog box. Of course, for the contained components to be visible the container must itself be
displayed, as the container effectively 'owns' its components. The container also controls how its
embedded components are laid out by means of a
layout
manager
.
Before we look at what a layout manager is, and how the layout of the components in a container is
determined, let's look into the basic methods defined in the
Container
class, and therefore available
to all containers.
You can find out about the components in a container object by using the following methods defined in
the
Container
class:
Method
Description
int
getComponentCount()
Returns a count of the number of components
contained by the current component.
Component
getComponent
(int
index)
Returns the component identified by the
index
value. The
index
value is an array index so it must
be between 0 and one less than the number of
components contained, otherwise an
ArrayIndexOutOfBoundsException
will be
thrown.
Component[]getComponents()
Returns an array of all the components in the
current container.
If we have a
Container
object,
content
, perhaps the content pane of a
JFrame
window, we could
iterate through the components in the
Container
with the following statements: