Java Reference
In-Depth Information
defined in
JComponent
). The
setBackground
and
setFont
methods are used to
change the background color and font associated with a
Component
. They
require a
Color
and
Font
object, respectively. Finally, the
show
method makes a
component visible. Its typical use is for a
JFrame
.
In the AWT, a
Container
is the abstract superclass representing all components
that can hold other components. An example of an AWT
Container
is the
Window
class, which represents a top-level window. As the inheritance hierar-
chy shows, a
Container
IS-A
Component
. A particular instance of a
Container
object will store a collection of
Component
s as well as other
Container
s.
The container has a useful helper object called a
LayoutManager
, which is a
class that positions components inside the container. Some useful methods are
A
Container
is the
abstract super-
class representing
all components that
can hold other
components.
void setLayout( LayoutManager mgr );
void add( Component comp );
void add( Component comp, Object where );
Layout managers are described in Section B.3.1. A container must first
define how objects in the container should be arranged. This is done by using
setLayout
. It then adds the objects into the container one-by-one by using
add
.
Think of the container as a suitcase, in which you can add clothes. Think of the
layout manager as the packing expert who will explain how clothes are to be
added to the suitcase.
As Figure B.2 shows, there are two types of
Container
objects, namely
The basic contain-
ers are the top-
level
Window
and
JComponent
. The
typical heavy-
weight compo-
nents are
JWindow
,
JFrame
, and
JDialog
.
1.
The top-level windows, which eventually reaches
JFrame
2.
The
JComponent
, which eventually reaches most other Swing
components
JFrame
is an example of a “heavyweight component,” while all Swing
components in the
JComponent
hierarchy are “lightweight.” The basic differ-
ence between heavyweight and lightweight components is that lightweight
components are drawn on a canvas entirely by Swing whereas heavyweight
components interact with the native windowing system. As a result, light-
weight components can add other lightweight components (for instance, you
can use
add
to place several
JButton
objects in a
JPanel
), but you should not
add
directly into a heavyweight component. Instead you obtain a
Container
representing its “content pane” and
add
into the content pane, thus allowing
Search WWH ::
Custom Search