This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
What you need to implement is called a "point in a polygon" algorithm.
It would be better for you if you could find an article dedicated to describing that algorithm for you.
Basically it says that you (as the programmer) should already know the maximum points of your polygon.
step 1. get the users coordinates step 2. theoretically draw a straigh line from that point to the one of the max points of your polygon. step 3. count the number of times you cross your polygon. step 4. if it's even then you are outside your poly, if odd, then you are inside it.
It's much easier to demo it by hand...
1. draw a square on a piece of paper. 2. put your pencil in the middle of the square and draw a line to the right all the way across the paper (until you have drawn it outside of the square) 3. count how many times you have crossed a line on your square. If you have crossed one line then you are inside, if you have crossed two lines then you are outside.
You can use any shape for this to be true.
Joined: Sep 01, 2004
Thanks jefff, On paper I can see how this works for any polygon and using a square it would be easy to see that I have crossed a line, especially if I had drawn the square using drawLine(x0,y0,x1,y1) four times. However how do I know that I have crossed a line if I use drawPolygon(x,y,n)? I had hoped for a way to check the color at the point(x,y). If it was green for example then I must be inside the green polygon. I suppose that life just isn't that easy. It's late here and perhaps in the morning the logic will be clear. I live in hope! Rob
This post is ancient history, but I'd like to log my belated thanks to Craig. I was also having problems cracking this one, but I cut and pasted Craig's code, ran it and finally annotated it until I knew what was going on.
Finally (it took about three hours ) the penny dropped... the listener is the PANEL in which the polygons are drawn, not the polygons themselves. Once the panel says it's clicked THEN you check to see if it's inside a polygon. :") It ALWAYS seems embarrassingly obvious once you understand...
Anyhow, just to let you know that your help is still bearing fruit even 2 years later!
"I was born in a water moon..."
The Algebraist by Iain M. Banks