我已经实现了一个简单的鼠标监听器,只要鼠标进入组件(JPanel),背景颜色就会发生变化,只要鼠标离开,它就会恢复原状。这有一些问题:
- 有时鼠标移动得太快以至于 mouseExit 事件没有被触发
- 如果我的组件有子组件,当鼠标移动到子组件时它会触发 mouseExit
- 如果我将鼠标快速移动到 child 身上,mouseEnter 事件不会被触发
我猜这对 Swing 老手来说很简单。对于如何解决这个问题,有任何的建议吗?我不想使用计时器之类的...
最佳答案
If I move the mouse over to the childs quickly, the mouseEnter event is not fired
我从未见过这种情况发生,但如果这是一个问题,那么您可以处理 mouseMoved 而不是重置背景。
If my component has childs, when the mouse moves to the childs it triggers the mouseExit
使用下面的测试,代码只会在你离开组件边界时执行:
public void mouseExited(MouseEvent e)
{
if (! getVisibleRect().contains(e.getPoint()) )
{
setBackground(...);
}
}
关于Java Swing : change background color on mouse over,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1882055/