1 /* 2 * File: MyPolygon.java 3 * 4 * Custom polygon class for Java 1.0.2 5 * 6 * Copyright: Northeast Parallel Architectures Center 7 * 8 */ 9 10 import java.awt.Polygon; 11 import java.awt.Graphics; 12 import java.awt.Point; 13 14 class MyPolygon extends Polygon { 15 16 // MyPolygon constructor #1: 17 public MyPolygon() { 18 // invoke the no-argument constructor of the superclass: 19 super(); 20 } 21 22 // MyPolygon constructor #2: 23 public MyPolygon( int[] xpoints, int[] ypoints, int npoints ) { 24 25 // invoke a constructor of the superclass: 26 super( xpoints, ypoints, npoints ); 27 28 } 29 30 /* 31 * MyPolygon constructor #3 32 * 33 * A regular n-gon with center (x,y) and radius r 34 * 35 */ 36 37 public MyPolygon( int x, int y, int r, int n ) { 38 39 // invoke the no-argument constructor of the superclass: 40 super(); 41 42 double theta = 2 * Math.PI/n; 43 double cos_theta = Math.cos( theta ); 44 double sin_theta = Math.sin( theta ); 45 46 int dx, dy; 47 int old_x, old_y; 48 49 int new_x = x, new_y = y - r; 50 this.addPoint( new_x, new_y ); 51 for ( int i = 1; i < n; i++ ) { 52 old_x = new_x; old_y = new_y; 53 dx = old_x - x; dy = old_y - y; 54 new_x = ( int ) Math.round( x + dx * cos_theta - dy * sin_theta ); 55 new_y = ( int ) Math.round( y + dx * sin_theta + dy * cos_theta ); 56 this.addPoint( new_x, new_y ); 57 } 58 59 } 60 61 // instance methods: 62 public void draw( Graphics g ) { 63 g.drawPolygon( this ); 64 } 65 public void fill( Graphics g ) { 66 g.fillPolygon( this ); 67 } 68 69 // rotate this polygon: 70 public MyPolygon rotate( double theta ) { 71 72 int dx, dy; 73 final double cos_theta = Math.cos( theta ); 74 final double sin_theta = Math.sin( theta ); 75 76 int x = this.getBoundingBox().x; 77 int y = this.getBoundingBox().y; 78 for ( int i = 0; i < this.npoints; i++ ) { 79 dx = this.xpoints[i] - x; 80 dy = this.ypoints[i] - y; 81 this.xpoints[i] = 82 ( int ) Math.round( x + dx * cos_theta - dy * sin_theta ); 83 this.ypoints[i] = 84 ( int ) Math.round( y + dx * sin_theta + dy * cos_theta ); 85 } 86 87 // return the rotated polygon as a side effect: 88 return this; 89 90 } 91 92 // overload Polygon.addPoint( int, int ): 93 public void addPoint( Point p ) { 94 super.addPoint( p.x, p.y ); 95 } 96 97 }