How to detect if a line is intersecting a rectangle?

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.

check out the Rectangle, Line, and Point classes. You can use the 2D implementations for double precision, and they have intersects() methods that’ll do exactly what you want. For example, Rectangle.intersects(Line) to get the collision you asked for.

If nothing else (and no doubt a bit late)

you can check using some simple arithmetic. If all else fails.

To do that, you need the slope of the line, which is, if memmory serves, (x2-x1)/(y2-y1).

From there, use y=mx+b, meaning (roughly), y=(slope*x val)+y starting point

then do a simple for loop though the values of x for the rectangle.

Something like this, I think.

int x1, x2, y1, y2;
int rx1, rx2, ry1, ry2;
//assign values, such that x1<=x2 and ry1<=ry2 and rx1<=rx2
double slope=(y2-y1)/(x2-x1); //if x2==x1, a problem is expected. (and I think it’s the right formula)
for(int x=rx1; x<=rx2; x++)
{
double yval=((slope)*(x-x1))+(y1<y2?y1:y2);
if(yVal<=ry2&&yval>=ry2)
return true;
}

I’m not sure if that’s exact, or if it’ll even compile, but with a bit of optimization, that should work…

I think.