import java.util.Arrays; import java.awt.Color; import java.awt.Point; /** * * Implementation of Shape as a Triangle, plus some Triangle-specific methods. * * @author Gene Fisher (gfisher@calpoly.edu) * */ public class ConvexPolygon extends Shape { /** Array of this' vertices */ private Point[] vertices; /** * Construct this by intializing the data fields to the values of given * parameters. */ public ConvexPolygon(Point[] vertices, Color color, boolean filled) { super(color, filled); this.vertices = vertices; } /** Return the indexth vertex */ public Point getVertex(int index) { return vertices[index]; } /** Set the indexth vertex */ public void setVertex(int index, Point vertex) { vertices[index] = vertex; } /** * Return true if super.equals is true, and all the vertices of the other * polygon are the same as this polygon. */ public boolean equals(Object other) { if (super.equals(other) == false) { return false; } /* * Note that this cast and subsequent code are safe, since super.equals * checks that other is not null and is the same class as this. */ ConvexPolygon cp = (ConvexPolygon) other; return Arrays.deepEquals(vertices, cp.vertices); // cute trick } /*-* * Specilized methods for ConvexPolygon */ public double getArea() { double a = 0; double b = 0; double[] x = new double[vertices.length + 1]; double[] y = new double[vertices.length + 1]; /* * Initialize array to calculate determinates. */ for (int i = 0; i < vertices.length; i++) { x[i] = vertices[i].x; y[i] = vertices[i].y; } /* * Make sure things are closed by settint the end point to the startimg * point. */ x[vertices.length] = vertices[0].x; y[vertices.length] = vertices[0].y; /* * Calculate the determinates. */ for(int i = 0; i < vertices.length; i++) { a += x[i] * y[i + 1]; b += y[i] * x[i + 1]; } /* * Apply the determinate-based formula. */ return Math.abs((a - b) / 2); } public void move(Point delta) { // Yipee, we got public data fields in java.awt.Point! for (int i = 0; i < vertices.length; i++) { vertices[i].x += delta.x; vertices[i].y += delta.y; } } public int numVertices() { return vertices.length; } public void addVertex(Point p) { int len = vertices.length; vertices = Arrays.copyOf(vertices, len + 1); vertices[len] = p; } /** * Return the Java AWT representation of this as a java.awt.Polygon */ public java.awt.Shape getAwtRep(int canvas_height) { int n = numVertices(); // number of vertices int[] xs= new int[n]; // array of vertex x coords int[] ys = new int[n]; // array normalized vertex y coords /* * Populate the x/y arrays, normalizing the y coords. */ for (int i = 0; i < n; i++) { xs[i] = getVertex(i).x; ys[i] = canvas_height - getVertex(i).y; } /* * Return the puppy. */ return new java.awt.Polygon(xs, ys, n); } }