This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I have a bunch of rectangles on a JPanel, and lines that connect some of the rectangles together. It represents a network map. I wrote the actionListener that handles the clicks on the rectangles. I simply map the x-y coordinates along with the height and width, then grab the points where the click occurred. Now I need a way to figure out if the click was on the lines that connect the rectangles. (Many of these lines are not vertical or horizontal, they make a diagonal across the screen. I am thinking I have to compute all the points the line hits by finding its slope of the line. Is there an easier way to do this? Any help would be greatly appreciated.
The Line2D and Rectangle2D apis have tantalizing methods that you can explore/experiment with for these kinds of things. For example, you could create a strategy based on one of the intersects methods with the help of a small Rectangle (instance member) in your event code. Center it over the coordinates of the mouse click and ask if it intersects any of the lines with intersectsLine(Line2D l) from the Rectangle2D api. Or you could ask the lines with intersects(Rectangle2D r) from the Line2D api.