0

I'm trying to write code that draws a polygon according to the user mouse clicks. I've figured out how to draw simple shapes such as segments (2 mouse clicks) how ever I'm facing a problem with creating a polygon (aka 3 or more mouse clicks).


    private  GUI_Shape_Collection _shapes = new ShapeCollection();
    private  GUI_Shape _gs;
    private  Color _color = Color.blue;
    private  boolean _fill = false;
    private  String _mode = "";
    private  Point_2D _p1;
    private  Polygon_2D pol;
    private  static Ex4 _winEx4 = null;

Segment is successfully being drawed. How ever the logic of catching the 3rd+ mouse clicks is a bit not clear to me.

private static void drawShape(GUI_Shape g) {
        StdDraw_Ex4.setPenColor(g.getColor());
        if(g.isSelected()) {StdDraw_Ex4.setPenColor(Color.gray);}
        GeoShape gs = g.getShape();
        boolean isFill = g.isFilled();

        if(gs instanceof Segment_2D){
            Segment_2D seg = (Segment_2D) gs;
            Point_2D p1 = ((Segment_2D) gs).get_p1();
            Point_2D p2 = ((Segment_2D) gs).get_p2();
            StdDraw_Ex4.line(p1.x(),p1.y(),p2.x(),p2.y());
        }
        
        if(gs instanceof Polygon_2D){
            Polygon_2D tri = (Polygon_2D) gs;
            Point_2D[] aP = tri.getAllPoints();
            double[] xValues = new double[tri.size()];
            double[] yValues = new double[tri.size()];
            for (int i = 0; i < tri.size(); i++) {
                                xValues[i] = aP[i].x();
                yValues[i] = aP[i].y();
            }
            if(isFill){
                StdDraw_Ex4.filledPolygon(xValues, yValues);
            } else {
                StdDraw_Ex4.polygon(xValues, yValues);
            }
        }


    }
    public void mouseMoved(MouseEvent e) {
        if(_p1!=null) {
            double x1 = StdDraw_Ex4.mouseX();
            double y1 = StdDraw_Ex4.mouseY();
            GeoShape gs = null;
            Point_2D p = new Point_2D(x1,y1);

            if(_mode.equals("Segment")){
                double d = _p1.distance(p);
                gs = new Segment_2D(_p1,p);
            }
            if(_mode.equals("Triangle")){
                if(pol.size() == 2){
                    gs = new Polygon_2D(pol);
                }
                pol.add(new Point_2D(p));
            }
            _gs = new GUIShape(gs,false, Color.pink, 0);
            drawShapes();
        }
    }



iVi
  • 31
  • 3

0 Answers0