Introduction to Java Programming-Comprehensive Version (6th Edition)

 

[Page 436 ( continued )]

13.8. Drawing Arcs

An arc is conceived as part of an oval bounded by a rectangle. The methods to draw or fill an arc are as follows :

drawArc( int x, int y, int w, int h, int startAngle, int arcAngle); fillArc( int x, int y, int w, int h, int startAngle, int arcAngle);

Parameters x , y , w , and h are the same as in the drawOval method; parameter startAngle is the starting angle; arcAngle is the spanning angle (i.e., the angle covered by the arc). Angles are measured in degrees and follow the usual mathematical conventions (i.e., degrees is in the easterly direction, and positive angles indicate counterclockwise rotation from the easterly direction); see Figure 13.11.

Figure 13.11. The drawArc method draws an arc based on an oval with specified angles.

Listing 13.6 is an example of how to draw arcs; the output is shown in Figure 13.12.

Figure 13.12. The program draws four filled arcs.

(This item is displayed on page 437 in the print version)

Listing 13.6. DrawArcs.java

(This item is displayed on pages 436 - 437 in the print version)

1 import javax.swing.JFrame; 2 import javax.swing.JPanel; 3 import java.awt.Graphics; 4 5 public class DrawArcs extends JFrame { 6 public DrawArcs() { 7 setTitle( "DrawArcs" );


[Page 437]

8 add( new ArcsPanel()); 9 } 10 11 /** Main method */ 12 public static void main(String[] args) { 13 DrawArcs frame = new DrawArcs(); 14 frame.setLocationRelativeTo( null ); // Center the frame 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setSize( 250 , 300 ); 17 frame.setVisible( true ); 18 } 19 } 20 21 // The class for drawing arcs on a panel 22 class ArcsPanel extends JPanel { 23 // Draw four blazes of a fan 24 protected void paintComponent(Graphics g) { 25 super.paintComponent(g); 26 27 int xCenter = getWidth() / 2 ; 28 int yCenter = getHeight() / 2 ; 29 int radius = ( int )(Math.min(getWidth(), getHeight()) * . 4 ); 30 31 int x = xCenter - radius; 32 int y = yCenter - radius; 33 34 g.fillArc(x, y, 2 * radius, 2 * radius, , 30 ); 35 g.fillArc(x, y, 2 * radius, 2 * radius, 90 , 30 ); 36 g.fillArc(x, y, 2 * radius, 2 * radius, 180 , 30 ); 37 g.fillArc(x, y, 2 * radius, 2 * radius, 270 , 30 ); 38 } 39 }

Note

Angles may be negative. A negative starting angle sweeps clockwise from the easterly direction, as shown in Figure 13.13. A negative spanning angle sweeps clockwise from the starting angle. The following two statements draw the same arc:

g.fillArc(x, y, 2 * radius, 2 * radius, -30 , -20 ); g.fillArc(x, y, 2 * radius, 2 * radius, -50 , 20 );

Figure 13.13. Angles may be negative.

(This item is displayed on page 438 in the print version)

The first statement uses negative starting angle -30 and negative spanning angle -20 as shown in Figure 13.13(a). The second statement uses negative starting angle -50 and positive spanning angle 20, as shown in Figure 13.13(b).

 

Категории