Java Swing: change background color on mouse over

后端 未结 4 1665
半阙折子戏
半阙折子戏 2020-12-11 08:27

I\'ve implemented a simple mouse listener where the background color changes whenever the mouse enters the component (a JPanel), and it reverts back whenever the mouse leave

4条回答
  •  -上瘾入骨i
    2020-12-11 08:31

    If I move the mouse over to the childs quickly, the mouseEnter event is not fired

    I've never seen this to happen, but if it is an issue then you can handle mouseMoved instead to reset the background.

    If my component has childs, when the mouse moves to the childs it triggers the mouseExit

    Use the following test and the code will only be executed when you leave the components bounds:

    public void mouseExited(MouseEvent e) 
    {
        if (! getVisibleRect().contains(e.getPoint()) )
        {
            setBackground(...);
        }
    }
    

提交回复
热议问题