1

I am very new to Java Swing, and I am working on an assignment. I have some polygons on my component. When I entered in to a polygon it has to highlight (i.e. filled with some color).

When I go to next polygon it has to highlight and previous one should be erased (i.e normal state). I found some examples but those are using "mousepressed" events, but mine is different.

halfer
  • 19,824
  • 17
  • 99
  • 186
ran
  • 667
  • 4
  • 9
  • 16
  • 3
    Why not look at this related [example](https://sites.google.com/site/drjohnbmatthews/point-in-polygon) and post an [sscce](http://sscce.org). – trashgod May 23 '11 at 23:02

2 Answers2

4

Have you gone through the MouseListener/MouseMotionListener sections of the Swing tutorials? If not, and if you have nothing written yet, I suggest that you review the tutorials and look at using the MouseMotionListener. You don't want to listen for mouseEntered but more likely mouseMoved. A pseudocode example could be:

in MouseMotionListener or MouseAdapter
   mouseMoved method
      get position of mouse pointer via the MouseEvent parameter.
      For loop through list of Polygons 
         If mouse inside of polygon, highlight it.
         Else, un-highlight it.
      End for loop
   End of mouseMoved method.
end MouseMotionListener or MouseAdapter
halfer
  • 19,824
  • 17
  • 99
  • 186
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • thank you so much for your help. i tried with the mousemoved event but my condition is when we enter in to polygon it has to highlight and when we exit it should go to normal state. but with the mouse moved event everytime when i moves the mouse even with in th polygon it refreshing(blinking). so is there any other way to do this. thank you so much for spending your valuable time for me. – ran May 24 '11 at 17:32
  • @ran: no, this is the best way. If it's not working for you, then your logic is wrong and you will need to post code. – Hovercraft Full Of Eels May 24 '11 at 18:37
  • Yes...i figured out mousemoved event is the best way to do..i changed my logic little bit..and then it is working fine.. – ran Sep 25 '12 at 21:03
2

java.awt.Polygon has a contains(double x, double y) method that returns true if the x,y mouse coordinates are inside the polygon.

The (x,y) coordinates come from implementing a MouseMotionListener on the Container where you're drawing your shapes and in the implemented public void mouseMoved(MouseEvent e) method you have e.getX() and e.getY() to get the coordinates and check if they're in your polygon(s).

mut1na
  • 795
  • 6
  • 21