Java Reference
In-Depth Information
Display 17.6
A
JFrame
with Color
(part 2 of 2)
R
ESULTING
GUI
You will need to use your mouse to
drag the top window or you will not see
the bottom window.
17.3
Containers and Layout Managers
Don't put all your eggs in one basket.
PROVERB
There are two main ways to create new classes from old classes. One way is to use
inheritance; this is known as the
Is-A relationship.
For example, an object of the class
ColoredWindow
in Display 17.6
is a
JFrame
because
ColoredWindow
is a derived
class of the class
JFrame
. The second way to create a new class from an existing class
(or classes) is to have instance variables of an already existing class type; this is known
as
composition
or the
Has-A relationship.
The Swing library has already set things up so
you can easily use composition. The actual code for declaring instance variables is in the
Swing library classes, such as the class
JFrame
. Rather than declaring instance variables,
add components to a
JFrame
using the
add
method. This does ultimately set some
instance variables, but this is done automatically when you use the
add
method. In this
section, we discuss adding and arranging components in a GUI or subpart of a GUI.
Thus far, we have only added one component, either a button or a label, to a
JFrame
.
You can add more than one component to a
JFrame
. To do so, use the
add
method
multiple times, but the
add
method simply tells which components are added to the
JFrame
; it does not say how they are arranged, such as side by side or one above the
other. To describe how the components are arranged, you need to use a
layout manager
.
In this section, we will see that there are other classes of objects besides
JFrame
s that
can have components added with the
add
method and arranged by a layout manager.
All these classes are known as
container classes
.
layout
manager
container
class