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

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

问题描述

我已经实现了一个简单的鼠标监听器哪里只要鼠标进入组件(一个JPanel),它会恢复只要鼠标离开背景颜色的变化。这有一些问题:


  • 有时候鼠标移动这么快的的 mouseExit 的事件不解雇

  • 如果我的组件有孩子的,当鼠标移动到孩子的它触发的 mouseExit

  • 如果我快速移动鼠标到孩子的,在的MouseEnter 的事件不解雇

我猜这是一个容易的摆动退伍军人。任何建议如何解决这一问题?我很想不使用定时器和这样的...


解决方案

  

如果我把鼠标移动到孩子的
  很快,MouseEnter事件不
  燃


我从来没有见过这样的事情发生,但如果它是一个问题,那么你可以处理的mouseMoved而不是重置背景。


  

如果我的组件有孩子的,当
  鼠标移动到它触发了孩子的
  在mouseExit


当你离开组件的边界使用下面的测试和code才会执行:

 公共无效的mouseExited(的MouseEvent E)
{
    如果(!getVisibleRect()。含有(e.getPoint()))
    {
    的setBackground(...);
    }
}

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:

  • 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

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...

解决方案

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

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

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