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 are components on the JPanel and the mouse goes over one of them it is detected as an exit on the JPanel, even though the component is on the JPanel. I was wondering whether anyone knows any way to solve this problem without doing something like adding listeners onto all components on the JPanel?
Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons. Tracking the cursor's motion involves significantly more system overhead than tracking other mouse events.
To register a handler object, you invoke the source object's registration method; for example, button. setOnAction (handler) for registering a handler for a button action event. To implement a handler interface, you implement the method defined in the handler interface.
MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse events. are of two types. MouseListener handles the events when the mouse is not in motion.
mouseDragged. Invoked when a mouse button is pressed on a component and then dragged.
There is a very easy solution for this problem that can work :
public class MyJPanel implements MouseListener {
public void mouseExited(MouseEvent e) {
java.awt.Point p = new java.awt.Point(e.getLocationOnScreen());
SwingUtilities.convertPointFromScreen(p, e.getComponent());
if(e.getComponent().contains(p)) {return;}
...//the rest of your code
}
...
}
This way you just ignore the mouseExited event when it occurs on a child element.
Here is one way to do it for a component 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 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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With