Java Reference
In-Depth Information
Display 17.11
Using Panels
(part 4 of 4)
Resulting GUI (After clicking Gray button)
Adding Color
You color a
JFrame
as follows:
JFrame_Object
.getContentPane().setBackground(
Color
);
If this is inside a constructor for the
JFrame
, then the expression simplifies to
getContentPane().setBackground(
Color
);
or the equivalent
this
.getContentPane().setBackground(
Color
);
You color a button, label, or any other component (which is not a
JFrame
) as follows:
Component_Object
.setBackground(
Color
);
Note that
getContentPane()
is only used with a
JFrame
.
EXAMPLE (INSIDE A CONSTRUCTOR FOR A DERIVED CLASS OF
JFrame
)
getContentPane().setBackground(Color.WHITE);
JButton redButton =
new
JButton("Red");
redButton.setBackground(Color.RED);
The
Container
Class
The class called
Containe
r is in the
java.awt
package. Any descendent class of the
class
Container
can have components added to it (or, more precisely, can have compo-
nents added to objects of the class). The class
JFrame
is a descendent class of the class
Container