Page 709 - Introduction to Programming with Java: A Problem Solving Approach
P. 709

                Color Named Constants
Let’s now talk about color values. You can specify color values with named constants or with instantiated Color objects. We’ll start with named constants.
The Color class defines this set of named constants: Color.BLACK Color.GREEN Color.RED
Color.BLUE Color.LIGHT_GRAYColor.WHITE
Color.CYAN Color.MAGENTA Color.YELLOW
Color.DARK_GRAY Color.ORANGE
Color.GRAY Color.PINK
As is customary, the named constants are class members. As with all class members, they are accessed us- ing <class name> dot syntax. In other words, they are accessed with a “Color.” prefix.
The Color class is in the java.awt package, so don’t forget to import that package when working with colors.
Color Objects
To obtain a color that is not in the Color class’s list of named constant colors, instantiate a Color object
with a specified mixture of red, green, and blue. Here’s the Color constructor call syntax: new Color(<red 0–255>, <green 0–255>, <blue 0–255>)
Each of the three Color constructor arguments is an int value between 0 and 255. The int value repre- sents an amount of color, with 0 indicating no color and 255 indicating the maximum amount of color. For
Apago PDF Enhancer
example, this line sets a button’s background color to a dark magenta:
button.setBackground(new Color(128, 0, 128));
The instantiated Color object uses half the maximum for red (128), no green (0), and half the maximum for blue (128). In the brightest magenta, increase the red and blue values from 128 to 255.
White light is the combination of all colors,4 so new Color(255, 255, 255) produces white. Blackistheabsenceofallcolors,sonew Color(0, 0, 0)producesblack.
This technique of creating a color by mixing specified amounts of red, green, and blue is used by many programming languages. The red, green, blue 3-tuple is commonly referred to as an RGB value. When com- ing up with RGB values for your programs, it’s perfectly acceptable to use trial and error, but to save time, you may want to visit an RGB color table online. For example—http://www.pitt.edu/~nisg/cis/web/cgi/rgb.html.
JFrame Background Color
Setting the background color for a JFrame window is slightly trickier than setting it for a component. First you have to get the JFrame’s content pane, and then you have to apply the background color to it. As shown below, the content pane is the inner part of the JFrame.
4 In 1666, Isaac Newton discovered that white light is composed of all of the colors of the color spectrum. He showed that when white light is passed through a triangular prism, it separates into different colors. And when the resulting colors are passed through a sec- ond triangular prism, they are brought back together to form the original white light.
16.16 Color 675
          c
c
o
o
n
n
t
t
e
en
n
t
tp
p
a
a
n
n
e
e
         























































   707   708   709   710   711