检测 JPanel 上的鼠标移动事件
我有一个 JPanel,我想检测以下事件
(1) 当鼠标移入时
(2) 当鼠标移出时
(1) 非常简单。 (2)有点棘手。 目前,我必须在 JPanel 周围的所有组件上注册事件。 如果 JPanel 周围的邻居检测到鼠标移动事件,这也意味着 JPanel 处于 (2) 的情况。 然而,这是一个相当肮脏的方法,当我将来添加新组件时,这个肮脏的解决方法将会被破坏。
另一种方法是使用计时器来监视 JPanel。 如果鼠标位置在 x 秒内不在 JPanel 内,我可以认为 JPanel 发生了鼠标移出事件。
然而,这对我来说似乎也是一种肮脏的方式,因为有一个单独的计时器来执行这样的常见任务是矫枉过正的。
有没有更好的方法,哪个Java平台可以提供?
I have a JPanel, which I would like to detect the following events
(1) When the mouse move in
(2) When the mouse move out
The (1) is quick easy. (2) is a bit tricky. Currently, I have to register event at all the components around JPanel. If the neighbor around JPanel detected a mouse move in event, this also means that JPanel is having (2) situation. However, this is a rather dirty away, as I add in new components in the future, this dirty workaround will break.
Another method is to have a timer to monitor the JPanel. If the mouse position is not within JPanel within x seconds, I can consider JPanel is having mouse move out event.
However, this seem a dirty way to me too, as having a separate timer to perform such common task is overkill.
Is there any better way, which Java platform may provide?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让您的类实现 MouseListener 并将其添加为最外层面板上的鼠标侦听器。 当鼠标在面板上移动时,您应该收到鼠标进入事件,当鼠标离开面板时,您应该收到鼠标退出事件; 无论面板包含什么组件。
来自 JavaDoc:
Have your class implement MouseListener and add it as a mouse listener on the outermost panel. You should get a mouse-entered event when the mouse moves over the panel, and mouse-exited when it leaves; regardless of whatever components the panel contains.
From the JavaDoc: