Java Reference
In-Depth Information
32
// draw the rainbow near the bottom-center
33
int
centerX = getWidth() /
2
;
34
int
centerY = getHeight() -
10
;
35
36
// draws filled arcs starting with the outermost
37
for
(
int
counter = colors.length; counter >
0
; counter--)
38
{
39
// set the color for the current arc
40
g.setColor(colors[counter -
1
]);
41
42
// fill the arc from 0 to 180 degrees
43
g.fillArc(centerX - counter * radius,
44
centerY - counter * radius,
45
counter * radius *
2
, counter * radius *
2
,
0
,
180
);
46
}
47
}
48
}
// end class DrawRainbow
Fig. 7.25
|
Drawing a rainbow using arcs and an array of colors. (Part 2 of 2.)
Line 30 in
paintComponent
declares local variable
radius
, which determines the
radius of each arc. Local variables
centerX
and
centerY
(lines 33-34) determine the loca-
tion of the midpoint on the base of the rainbow. The loop at lines 37-46 uses control vari-
able
counter
to count backward from the end of the array, drawing the largest arcs first
and placing each successive smaller arc on top of the previous one. Line 40 sets the color
to draw the current arc from the array. The reason we have
Color.WHITE
entries at the
beginning of the array is to create the empty arc in the center. Otherwise, the center of the
rainbow would just be a solid violet semicircle. You can change the individual colors and
the number of entries in the array to create new designs.
The
fillArc
method call at lines 43-45 draws a filled semicircle. Method
fillArc
requires six parameters. The first four represent the bounding rectangle in which the arc
will be drawn. The first two of these specify the coordinates for the
upper-left
corner of the
bounding rectangle, and the next two specify its width and height. The fifth parameter is
the starting angle on the oval, and the sixth specifies the
sweep
, or the amount of arc to
cover. The starting angle and sweep are measured in degrees, with zero degrees pointing
right. A
positive
sweep draws the arc
counterclockwise
, while a
negative
sweep draws the arc
clockwise
. A method similar to
fillArc
is
drawArc
—it requires the same parameters as
fillArc
, but draws the edge of the arc rather than filling it.
Class
DrawRainbowTest
(Fig. 7.26) creates and sets up a
JFrame
to display the
rainbow. Once the program makes the
JFrame
visible, the system calls the
paintCompo-
nent
method in class
DrawRainbow
to draw the rainbow on the screen.
1
// Fig. 7.26: DrawRainbowTest.java
2
// Test application to display a rainbow.
3
import
javax.swing.JFrame;
4
5
public
class
DrawRainbowTest
6
{
Fig. 7.26
|
Test application to display a rainbow. (Part 1 of 2.)