@@ -18,6 +18,7 @@ public class LineSegment extends PaintComponent {
1818 private Color defaultColor ;
1919 private Color selectColor ;
2020 private Stroke stroke ;
21+ private double strokeWidth ;
2122
2223 /**
2324 * @return the toPoint
@@ -57,6 +58,7 @@ public LineSegment(SimplePoint fromPoint, SimplePoint toPoint,
5758 this .defaultColor = defaultColor ;
5859 this .selectColor = selectColor ;
5960 this .stroke = new BasicStroke (strokeWidth );
61+ this .strokeWidth = strokeWidth ;
6062 }
6163
6264 public LineSegment (SimplePoint fromPoint , SimplePoint toPoint ) {
@@ -70,7 +72,7 @@ public LineSegment(SimplePoint fromPoint, SimplePoint toPoint) {
7072 @ Override
7173 protected void paintNotSelected (Graphics g ) {
7274 g .setColor (defaultColor );
73- ((Graphics2D )g ).setStroke (stroke );
75+ ((Graphics2D ) g ).setStroke (stroke );
7476 g .drawLine (fromPoint .getX (), fromPoint .getY (), toPoint .getX (),
7577 toPoint .getY ());
7678
@@ -79,16 +81,50 @@ protected void paintNotSelected(Graphics g) {
7981 @ Override
8082 protected void paintSelected (Graphics g ) {
8183 g .setColor (selectColor );
82- ((Graphics2D )g ).setStroke (stroke );
84+ ((Graphics2D ) g ).setStroke (stroke );
8385 g .drawLine (fromPoint .getX (), fromPoint .getY (), toPoint .getX (),
8486 toPoint .getY ());
8587 }
8688
8789 @ Override
88- public Rectangle getBounds () {
89- return new Rectangle (fromPoint .getX (), fromPoint .getY (),
90- toPoint .getX () - fromPoint .getX (),
91- toPoint .getY () - fromPoint .getY ());
90+ public boolean contains (int x , int y ) {
91+ // if either end points contains, I do not contain
92+ if (fromPoint .contains (x , y ) || toPoint .contains (x , y )) {
93+ return false ;
94+ }
95+ // else return the D(curPoint , fromPoint) + D(curPoint, toPoint) ==
96+ // D(fromPoint, toPoint)
97+ double distanceBetweenXYandFrom = Math
98+ .sqrt (Math .pow (fromPoint .getX () - x , 2 )
99+ + Math .pow (fromPoint .getY () - y , 2 ));
100+ double distanceBetweenXYandTo = Math
101+ .sqrt (Math .pow (toPoint .getX () - x , 2 )
102+ + Math .pow (toPoint .getY () - y , 2 ));
103+ double distanceBetweenFromAndTo = Math
104+ .sqrt (Math .pow (toPoint .getX () - fromPoint .getX (), 2 )
105+ + Math .pow (toPoint .getY () - fromPoint .getY (), 2 ));
106+
107+ // checking delta distance
108+ // Note: this calculation is only an approximation
109+ if (Math .abs (distanceBetweenFromAndTo - distanceBetweenXYandFrom
110+ - distanceBetweenXYandTo ) < Math .sqrt (strokeWidth )) {
111+ return true ;
112+
113+ }
114+ return false ;
115+ }
116+
117+ @ Override
118+ public void translate (int i , int j ) {
119+ super .translate (i , j );
120+ // if from and to points are not selected, translate them as well
121+ if (this .fromPoint .isSelected () == false ){
122+ this .fromPoint .translate (i , j );
123+ }
124+ if (this .toPoint .isSelected () == false ){
125+ this .toPoint .translate (i , j );
126+ }
127+
92128 }
93129
94130}
0 commit comments