Java Reference
In-Depth Information
object you pass your own parameter values for the redness, greenness, and blue-
ness of the color:
new Color(<red>, <green>, <blue>)
The red/green/blue components should be integer values between 0 and 255 . The
higher the value, the more of that color is mixed in. All 0 values produce black, and all
255 values produce white. Values of (0, 255, 0) produce a pure green, while values
of (128, 0, 128) make a dark purple color (because red and blue are mixed). Search
for “RGB table” in your favorite search engine to find tables of many common colors.
The following program demonstrates the use of custom colors. It uses a class con-
stant for the number of rectangles to draw and produces a blend of colors from black
to white:
1 // Draws a smooth color gradient from black to white.
2
3 import java.awt.*;
4
5 public class DrawColorGradient {
6
public static final int RECTS = 32;
7
8
public static void main(String[] args) {
9
DrawingPanel panel = new DrawingPanel(256, 256);
10
panel.setBackground( new Color(255, 128, 0)); // orange
11
12
Graphics g = panel.getGraphics();
13
14
// from black to white, top left to bottom right
15
for ( int i = 0; i < RECTS; i++) {
16
int shift = i * 256 / RECTS;
17
g.setColor( new Color(shift, shift, shift));
18
g.fillRect(shift, shift, 20, 20);
19
}
20
}
21 }
This program produces the output shown in Figure 3G.9.
It is also legal to store a Color object into a variable or pass it as a parameter. For
example, we could have written the coloring code in the preceding program as follows:
Color c = new Color(shift, shift, shift);
g.setColor(c);
...
We will use this idea later when parameterizing colors in this chapter's Case Study.
 
Search WWH ::




Custom Search