import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class PolygonTest extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Polygon triangle = new Polygon(3); triangle.add(new Point2D.Double(40, 40)); triangle.add(new Point2D.Double(120, 160)); triangle.add(new Point2D.Double(20, 120)); double x = 200; double y = 200; double r = 50; Polygon pentagon = new Polygon(5); for (int i = 0; i < 5; i++) pentagon.add(new Point2D.Double( x + r * Math.cos(2 * Math.PI * i / 5), y + r * Math.sin(2 * Math.PI * i / 5))); triangle.draw(g2); pentagon.draw(g2); } } /** A polygon is a closed curve made up from line segment that join the corner points. */ class Polygon { /** Constructs a polygon with a given number of corner points. @param n the number of corner points. */ public Polygon(int n) { corners = new Point2D.Double[n]; cornersSize = 0; } /** Adds a corner point of the polygon. The point is ignored if the maximum number of points has been added. @param p the corner point */ public void add(Point2D.Double p) { if (cornersSize < corners.length) { corners[cornersSize] = p; cornersSize++; } } /** Draws the polygon. @param g2 the graphics context */ public void draw(Graphics2D g2) { for (int i = 0; i < cornersSize; i++) { Point2D.Double from = corners[i]; Point2D.Double to = corners[(i + 1) % corners.length]; g2.draw(new Line2D.Double(from, to)); } } private Point2D.Double[] corners; private int cornersSize; }