I have a problem with a simple thing I didn’t believe would cause me so much trouble. I have a JPanel on which I can draw lines. Each line is defined by an object which holds the (x,y) coordinates. So now I have an “eraser” tool, and I want to erase those lines.
The whole thing should work like this: I set eraseMode = true, and the mouse pointer turns into a 10x10 square. When the mouse is dragged on the panel, it should delete every line that intersects with the mouse’s square. So I thought I would use the simplest (but not most optimal) solution, and have two for loops, i and j. i goes from 0 to 9, and j from 0 to 9, and they make a combination of 100 different points from which at least one needs to be on the line to get the line deleted. The line is defined by (m1.x,m1.y) and (m2.x,m2.y), and my formula for detecting if the point (i,j) is on the line is:
int lambda = i*(m2.y - m1.y) - j*(m2.x - m1.x) + m1.ym2.x - m1.xm2.y;
if (lambda == 0) deleteLine(m1,m2);
The problem is that the line rarely gets deleted. I checked with various values getting println’d and as far as I could figure, the problem is this formula is not getting called enough times. In most cases the value of lambda is “close” to 0, but it almost never is exactly zero. Which would mean that the function gets called, let’s say, 10 times per second, so I would have to drag the mouse real slow to archieve something. I also tried deleting the line when lambda is between (-100, 100) but I only ended up deleting lines that were not underneith the 10x10 square.
So could someone help me with this? I basically want to check if a line defined by two points intersects a rectangle, and if it does then delete that line.