Java Reference
In-Depth Information
7.17 (Optional) GUI and Graphics Case Study: Drawing
Arcs
Using Java's graphics features, we can create complex drawings that would be more tedious
to code line by line. In Figs. 7.25-7.26, we use arrays and repetition statements to draw a
rainbow by using Graphics method fillArc . Drawing arcs in Java is similar to drawing
ovals—an arc is simply a section of an oval.
In Fig. 7.25, lines 10-11 declare and create two new color constants— VIOLET and
INDIGO . As you may know, the colors of a rainbow are red, orange, yellow, green, blue,
indigo and violet. Java has predefined constants only for the first five colors. Lines 15-17
initialize an array with the colors of the rainbow, starting with the innermost arcs first. The
array begins with two Color.WHITE elements, which, as you'll soon see, are for drawing the
empty arcs at the center of the rainbow. The instance variables can be initialized when
they're declared, as shown in lines 10-17. The constructor (lines 20-23) contains a single
statement that calls method setBackground (which is inherited from class JPanel ) with
the parameter Color.WHITE . Method setBackground takes a single Color argument and
sets the background of the component to that color.
1
// Fig. 7.25: DrawRainbow.java
2
// Drawing a rainbow using arcs and an array of colors.
3
import java.awt.Color;
4
import java.awt.Graphics;
5
import javax.swing.JPanel;
6
7
public class DrawRainbow extends JPanel
8
{
9
// define indigo and violet
10
private final static Color VIOLET = new Color( 128 , 0 , 128 );
11
private final static Color INDIGO = new Color( 75 , 0 , 130 );
12
13
// colors to use in the rainbow, starting from the innermost
14
// The two white entries result in an empty arc in the center
15
private Color[] colors =
16
{ Color.WHITE , Color.WHITE , VIOLET , INDIGO , Color.BLUE ,
17
Color.GREEN , Color.YELLOW , Color.ORANGE , Color.RED };
18
19
// constructor
20
public DrawRainbow()
21
{
22
setBackground( Color.WHITE ); // set the background to white
23
}
24
25
// draws a rainbow using concentric arcs
26
public void paintComponent(Graphics g)
27
{
28
super .paintComponent(g);
29
30
int radius = 20 ; // radius of an arc
31
Fig. 7.25 | Drawing a rainbow using arcs and an array of colors. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search