Java Reference
In-Depth Information
Color
You can set the color of a
JFrame
(or other GUI object). To set the background color
of a
JFrame
, use
getContentPane().setBackground(
Color
);
For example, the following will set the color of the
JFrame
named
someFrame
to blue:
getContent
Pane
set
Background
someFrame.getContentPane().setBackground(Color.BLUE);
Alternatively, if you set the color in the constructor for the
JFrame
, the invocation
takes the form
Color.BLUE
getContentPane().setBackground(Color.BLUE);
which is equivalent to
this
.getContentPane().setBackground(Color.BLUE);
The next Programming Example, “A GUI with a Label and Color,” shows a
JFrame
object (in fact, two of them) with color.
The method invocation
getContentPane()
returns something called the
content
pane
of the
JFrame
. So,
content pane
getContentPane().setBackground(Color.BLUE);
actually sets the color of the content pane to blue. The content pane is the “inside” of
the
JFrame
, so coloring the content pane has the effect of coloring the inside of the
JFrame
. However, you can think of
getContentPane().setBackground(
Color
);
as a peculiarly spelled method invocation that sets the color of the
JFrame
. (In this
book, we will not be referring to the content pane of a
JFrame
except when we want to
color the
JFrame
, so we will explain the content pane no further.)
Use
getContentPane
only when you give color to a
JFrame
. As you will see, to set
the color of some component in a
JFrame
, such as a button, simply use the method
setBackground
with the button or other component as the calling object. You will see
examples of adding color to components in Section 17.3.
What kind of thing is a
color
when used in a Java Swing class? Like everything
else in Java, a color is an object—in this case, an object that is an instance of the class
Color
. The class
Color
is in the
java.awt
package. (Note that the package name is
java.awt
, not
javax.awt
. )
In a later chapter, you will see how you can define your own colors, but for now
we will use the colors that are already defined for you, such as
Color.BLUE
, which
is a constant named
BLUE
that is defined in the class
Color
. The constant, of course,
represents the color blue. If you set the background of a
JFrame
to
Color.BLUE
, then
the
JFrame
will have a blue background. The type of the constant
Color.BLUE
and
other such constants is
Color
. The list of color constants that are defined for you are
given in Display 17.5. The next Programming Example, “A GUI with a Label and
Color,” has an example of a constructor with one parameter of type
Color
.
get
Content
Pane
color
Color