1 /* 2 * File: OctagonTest.java 3 * 4 * Draw a regular octagon 5 * 6 * Copyright: Northeast Parallel Architectures Center 7 * 8 */ 9 10 import java.applet.Applet; 11 import java.awt.Graphics; 12 import java.awt.Color; 13 import java.awt.Polygon; 14 import java.awt.Point; 15 16 public class OctagonTest extends Applet { 17 18 // create a reference to an octagon: 19 private Octagon octagon; 20 21 // create references to eight points: 22 private Point p1, p2, p3, p4, p5, p6, p7, p8; 23 24 public void init() { 25 26 // instantiate eight points (the vertices of a regular octagon): 27 p1 = new Point( 69, 25 ); 28 p2 = new Point( 131, 25 ); 29 p3 = new Point( 175, 69 ); 30 p4 = new Point( 175, 131 ); 31 p5 = new Point( 131, 175 ); 32 p6 = new Point( 69, 175 ); 33 p7 = new Point( 25, 131 ); 34 p8 = new Point( 25, 69 ); 35 36 // instantiate an octagon like this... 37 octagon = new Octagon( p1, p2, p3, p4, p5, p6, p7, p8 ); 38 39 // ...or like this: 40 octagon = new Octagon(); 41 octagon.addPoint( p1 ); 42 octagon.addPoint( p2 ); 43 octagon.addPoint( p3 ); 44 octagon.addPoint( p4 ); 45 octagon.addPoint( p5 ); 46 octagon.addPoint( p6 ); 47 octagon.addPoint( p7 ); 48 octagon.addPoint( p8 ); 49 // (see below for the definition of addPoint( Point ) ) 50 51 } 52 53 public void paint( Graphics g ) { 54 55 // fill the octagon: 56 g.setColor( Color.red ); 57 octagon.fill( g ); 58 59 } 60 61 } 62 63 // An octagon is a polygon with eight sides: 64 class Octagon extends Polygon { 65 66 // Octagon constructor #1: 67 public Octagon() { 68 // invoke the constructor of the superclass Polygon: 69 super(); 70 } 71 72 // Octagon constructor #2: 73 public Octagon( int x1, int y1, 74 int x2, int y2, 75 int x3, int y3, 76 int x4, int y4, 77 int x5, int y5, 78 int x6, int y6, 79 int x7, int y7, 80 int x8, int y8 ) { 81 82 // invoke the constructor of the superclass Polygon: 83 super(); 84 85 // the 'this' reference is optional: 86 this.addPoint( x1, y1 ); 87 this.addPoint( x2, y2 ); 88 this.addPoint( x3, y3 ); 89 this.addPoint( x4, y4 ); 90 this.addPoint( x5, y5 ); 91 this.addPoint( x6, y6 ); 92 this.addPoint( x7, y7 ); 93 this.addPoint( x8, y8 ); 94 95 } 96 97 // Octagon constructor #3: 98 public Octagon( Point p1, 99 Point p2, 100 Point p3, 101 Point p4, 102 Point p5, 103 Point p6, 104 Point p7, 105 Point p8 ) { 106 107 // invoke Octagon constructor #2: 108 this( p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, 109 p5.x, p5.y, p6.x, p6.y, p7.x, p7.y, p8.x, p8.y ); 110 111 } 112 113 // Instance methods: 114 public void draw( Graphics g ) { 115 g.drawPolygon( this ); 116 } 117 public void fill( Graphics g ) { 118 g.fillPolygon( this ); 119 } 120 121 // Overload Polygon.addPoint( int, int ): 122 public void addPoint( Point p ) { 123 super.addPoint( p.x, p.y ); 124 } 125 126 }