Sunday, July 8, 2012

Mouse Click in a Triangular Region


It is relatively easy to test whether a mouse click occurs inside a rectangular region. However, testing mouse click in triangular region is less obvious. In this article, we will draw a cross inside a window to separate the screen into four triangular regions, and then we will write a mouse click handler so that it will report which region is clicked.

Drawing a cross

We will first write a program to draw a cross as shown below:

The drawing code should be simple enough to be understood. To test the code, copy and paste it to a file named, then issue:

java RegionClicker

Handling Mouse Click with a MouseAdapter

We are now going to handle the mouse click event. First we need to define a event handler. Right now it will just pop up a message box when mouse click occurs.

Then we need to tell Java we are listening to the mouse event of the label by adding the following line in main()

Recognizing the Triangular Region

The next thing we are going to do is let the program report which triangle is clicked. It will say "up","down","left" or "right" according to the region clicked. It seems to be complex at first, but the code is actually simple.

Two Points Form

To derive the above code, we will first find out the equations of the two diagonal. Looking at the line drawing code, we are actually drawing two lines:
line A: (0,0) to (300,300)
line B: (300,0) to (0,300)

Line A is joining the upper left corner to the lower right corner, whereas line B is joining the lower left corner to the upper right corner. The equations of both lines can be determined by the two points form.
line A : (y-0)/(x-0) = (300-0)/(300-0)
line B : (y-0)/(x-300) = (300-0)/(0-300)

line A : y = x
line B : y = 300-x

We know that all points lying in line A satisfy equation A, that is, it satisfy the following condition :
With a simple observation, all points lying above line A must satisfy :
and all points lying below line A must satisfy :
Similarly, we would make the same conclusion to line B:
if (y=300-x), then the point lies on line B
if (y<300-x), then the point is above line B
if (y>300-x), then the point is below line B

Combining the above, we have:

If (y<x) and (y<300-x) then the point is lying above line A and also line B, hence it is in the upper triangular region.

If (y<x) and (y>300-x) then the point is lying above line A but below line B, 
hence it is in the right triangular region,


The above code just handle window of 300x300. We can easily generalize the above code to a window of any size. The following program make dimension constants stored in W and H. And this is the completed version for this article.

No comments:

Post a Comment