11package actions ;
22
3+ import java .awt .Component ;
34import java .util .ArrayList ;
45
56import paintcomponents .LineSegment ;
@@ -20,12 +21,32 @@ public boolean canPerformAction() {
2021 //only two points can be selected
2122 if (items .size () != 2 ) return false ;
2223 //selected component must be of type point
24+
2325 for (PaintComponent paintComponent : items ) {
2426 if (!(paintComponent instanceof SimplePoint )){
2527 return false ;
2628 }
2729 }
28- //TODO If line segment already exists, do not add again!!!
30+
31+ //check if line segment already exist
32+ // if exists, then it will not form a new line segment
33+ ArrayList <PaintComponent > components = panel .getPaintComponents ();
34+ LineSegment line = null ;
35+
36+ //get all paintComponents
37+ for (PaintComponent paintComponent : components ) {
38+ if ( paintComponent instanceof LineSegment ) {
39+ line = (LineSegment ) paintComponent ;
40+ //check front point and to point similarities
41+ if (items .get (0 ) == line .getFromPoint () &&
42+ items .get (1 ) == line .getToPoint ())
43+ return false ;
44+ if (items .get (1 ) == line .getFromPoint () &&
45+ items .get (0 ) == line .getToPoint ())
46+ return false ;
47+ }
48+ }
49+
2950 //TODO Do not allow adding two line segments connecting the same point
3051 return true ;
3152
@@ -38,15 +59,25 @@ public void performAction() {
3859
3960 //construct line segment
4061 LineSegment lineSegment = new LineSegment ((SimplePoint )(items .get (0 )), (SimplePoint )(items .get (1 )));
62+
63+
64+ addLineSegment (lineSegment );
65+ }
66+ /**
67+ * This method updates the panel's list of paint components and selection after a line segment is added
68+ * Subclasses should call this method to update the panel when customizing the addition of a line segment
69+ *
70+ * @param lineSegment the lineSegment to be added to the painting panel
71+ */
72+ protected void addLineSegment (LineSegment lineSegment ) {
73+
4174 //add to panel
4275 panel .addPaintComponent (lineSegment );
4376
4477 //change selection
4578 panel .getSelectTool ().clearSelection ();
4679 panel .getSelectTool ().selectComponent (lineSegment );
4780 panel .repaint ();
48-
49-
5081 }
5182
5283 @ Override
0 commit comments