Java – detect mouse entry / exit events anywhere in JPanel

Basically, there is a JPanel. I want to know when the mouse enters the JPanel area and exits the JPanel area So I added a mouse listener, but if there are components on the JPanel and the mouse moves over one of them, it will be detected as an exit on the JPanel, even if the component is on the JPanel I wonder if anyone knows any way to solve this problem without adding listeners to all components on JPanel?

Solution

The following is one way to components that may contain other components:

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

Toolkit.getDefaultToolkit().addAWTEventListener( 
   new TargetedMouseHandler( panel ),AWTEvent.MOUSE_EVENT_MASK );

>Implement targetedmousehandler to ignore events that are not provided by the panel or a child of one of the panels (you can use swingutilities.isdescendingfrom to test) Tracks whether the mouse is already within the boundary of the panel When you get mouseevent in the panel or one of the children MOUSE_ Set the flag to true when entering an event. > When you get mouseevent MOUSE_ The flag is reset only when the point in mouseevent exceeds the boundary of the target panel SwingUtilities. Convertpoint and component getBounds(). Contains () will come in handy here

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>