Detecting mouse move event on JPanel

I have a JPanel that would like to detect the following events

(1) When the mouse moves to

(2) When the mouse moves

(1) fast simple. (2) a little tricky. Currently I have to log an event on all JPanel components. If a neighbor around the JPanel detects mouse movement in the event, it also means the JPanel has (2) a situation. However, this is rather messy, since I add new components in the future, this dirty workaround will break.

Another method is to have a timer to monitor the JPanel. If the mouse position is not within the JPanel for x seconds, I can consider that the JPanel has a mouse move event.

However, this strikes me as messy as having a separate timer to handle such a common task is overkill.

Is there a better way the Java platform can provide?

0


a source to share


1 answer


Have your class implement MouseListener and add it as a mouse listener on the outermost panel. You should receive a mouse-injected event when the mouse moves over the panel, and the mouse will exit when it leaves; no matter what components the panel contains.

From JavaDoc:



void mouseEntered (MouseEvent e) Called when the mouse enters the component.

void mouseExited (MouseEvent e) Called when the mouse exits the component.

+6


a source







All Articles