Question

I have a JPanel, which I would like to detect the following events

(1) When the mouse move in

(2) When the mouse move out

The (1) is quick easy. (2) is a bit tricky. Currently, I have to register event at all the components around JPanel. If the neighbor around JPanel detected a mouse move in event, this also means that JPanel is having (2) situation. However, this is a rather dirty away, as I add in 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 JPanel within x seconds, I can consider JPanel is having mouse move out event.

However, this seem a dirty way to me too, as having a separate timer to perform such common task is overkill.

Is there any better way, which Java platform may provide?

Was it helpful?

Solution

Have your class implement MouseListener and add it as a mouse listener on the outermost panel. You should get a mouse-entered event when the mouse moves over the panel, and mouse-exited when it leaves; regardless of whatever components the panel contains.

From the JavaDoc:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top