Detecting mouse enter/exit events anywhere on JPanel

前端 未结 5 1768
北海茫月
北海茫月 2020-12-06 05:36

Basically there is a JPanel on which I want to know when the mouse enters the area of the JPanel and exits the area of the JPanel. So I added a mouse listener, but if there

5条回答
  •  死守一世寂寞
    2020-12-06 06:00

    Here is one way to do it for a component that may contain other components:

    1. Add a global AWT event listener to get all mouse events. For example:

      Toolkit.getDefaultToolkit().addAWTEventListener( 
         new TargetedMouseHandler( panel ), AWTEvent.MOUSE_EVENT_MASK );
      
    2. Implement the TargetedMouseHandler to ignore events that aren't sourced by the panel or by one of the panel's children (you can use SwingUtilities.isDescendingFrom to test for this).

    3. Keep track of whether or not the mouse is already within the bounds of your panel. When you get a MouseEvent.MOUSE_ENTERED event in your panel or one of its children, set a flag to true.

    4. When you get a MouseEvent.MOUSE_EXITED event, only reset the flag if the point in the MouseEvent is outside the bounds of your target panel. SwingUtilities.convertPoint and Component.getBounds().contains() will come in handy here.

提交回复
热议问题