11package org .openpatch .scratch .extensions .shape ;
22
33import java .awt .geom .Path2D ;
4+ import java .awt .geom .Point2D ;
5+ import java .util .ArrayList ;
6+ import java .util .List ;
47
58/**
69 * Represents a polygon shape defined by its vertices.
710 */
811public class Polygon extends Shape {
912
13+ private final List <Point2D .Double > points = new ArrayList <>();
14+
1015 /**
11- * Creates a polygon with no points .
16+ * Creates an empty polygon .
1217 */
1318 public Polygon () {
1419 this .awtShape = new Path2D .Double ();
@@ -17,34 +22,44 @@ public Polygon() {
1722 /**
1823 * Creates a polygon with the specified vertices.
1924 *
20- * @param xPoints an array of x-coordinates of the polygon's vertices
21- * @param yPoints an array of y-coordinates of the polygon's vertices
25+ * @param xPoints an array of x-coordinates
26+ * @param yPoints an array of y-coordinates
2227 */
2328 public Polygon (double [] xPoints , double [] yPoints ) {
2429 if (xPoints .length != yPoints .length ) {
25- throw new IllegalArgumentException ("xPoints and yPoints must have same length" );
30+ throw new IllegalArgumentException ("xPoints and yPoints must have the same length" );
2631 }
27- var awtPath = new Path2D .Double ();
28- awtPath .moveTo (xPoints [0 ], yPoints [0 ]);
29- for (int i = 1 ; i < xPoints .length ; i ++) {
30- awtPath .lineTo (xPoints [i ], yPoints [i ]);
32+ this .awtShape = new Path2D .Double ();
33+ for (int i = 0 ; i < xPoints .length ; i ++) {
34+ addPoint (xPoints [i ], yPoints [i ]);
3135 }
32- awtPath .closePath ();
33-
34- this .awtShape = awtPath ;
3536 }
3637
3738 /**
3839 * Adds a point to the polygon.
3940 *
40- * @param x the x-coordinate of the point
41- * @param y the y-coordinate of the point
41+ * @param x the x-coordinate
42+ * @param y the y-coordinate
4243 */
4344 public void addPoint (double x , double y ) {
44- if (this .awtShape instanceof Path2D path ) {
45- path .lineTo (x , y );
46- } else {
47- throw new IllegalStateException ("Shape is not a Path2D" );
45+ points .add (new Point2D .Double (x , y ));
46+ rebuildPath ();
47+ }
48+
49+ /**
50+ * Rebuilds the Path2D from the stored points.
51+ */
52+ private void rebuildPath () {
53+ Path2D .Double path = new Path2D .Double ();
54+ if (!points .isEmpty ()) {
55+ Point2D .Double first = points .get (0 );
56+ path .moveTo (first .x , first .y );
57+ for (int i = 1 ; i < points .size (); i ++) {
58+ Point2D .Double p = points .get (i );
59+ path .lineTo (p .x , p .y );
60+ }
61+ path .closePath ();
4862 }
63+ this .awtShape = path ;
4964 }
5065}
0 commit comments