Java Swing:在鼠标悬停时更改背景颜色 [英] Java Swing: change background color on mouse over

查看:96
本文介绍了Java Swing:在鼠标悬停时更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个简单的鼠标侦听器,只要鼠标进入组件(JPanel),背景颜色就会发生变化,并且只要鼠标离开,它就会恢复.这有一些问题:

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 leaves. This has some problems:

  • 有时鼠标移动得太快,mouseExit 事件没有被触发
  • 如果我的组件有子组件,当鼠标移动到子组件时会触发 mouseExit
  • 如果我将鼠标快速移到子元素上,则不会触发 mouseEnter 事件
  • Sometimes the mouse moves so quick that the mouseExit event is not fired
  • If my component has childs, when the mouse moves to the childs it triggers the mouseExit
  • If I move the mouse over to the childs quickly, the mouseEnter event is not fired

我猜这对于 Swing 退伍军人来说是一件容易的事.对于如何解决这个问题,有任何的建议吗?我不想使用计时器之类的......

I'm guessing this is an easy one for Swing veterans. Any suggestions on how to fix this? I'd love not to use timers and such...

推荐答案

如果我将鼠标移到孩子身上很快,mouseEnter 事件不是开除

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

我从未见过这种情况发生,但如果这是一个问题,那么您可以处理 mouseMoved 来重置背景.

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(...);
    }
}

这篇关于Java Swing:在鼠标悬停时更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆