Detecting mouse enter/exit events anywhere on JPanel

前端 未结 5 1775
北海茫月
北海茫月 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:05

    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.

提交回复
热议问题