Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPanel actionListener to determine click on diagonal drawLine

 
Chris Carney
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic