简体   繁体   English

在JPanel上检测鼠标移动事件

[英]Detect Mouse Move Event On JPanel

I have a JPanel, which I would like to detect the following events 我有一个JPanel,我想检测以下事件

(1) When the mouse move in (1)当鼠标移入

(2) When the mouse move out (2)鼠标移出时

The (1) is quick easy. (1)快速简便。 (2) is a bit tricky. (2)有点棘手。 Currently, I have to register event at all the components around JPanel. 当前,我必须在JPanel的所有组件上注册事件。 If the neighbor around JPanel detected a mouse move in event, this also means that JPanel is having (2) situation. 如果JPanel周围的邻居在事件中检测到鼠标移动,则这也意味着JPanel处于(2)情况。 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. 另一种方法是有一个计时器来监视JPanel。 If the mouse position is not within JPanel within x seconds, I can consider JPanel is having mouse move out event. 如果鼠标位置在x秒内不在JPanel内,则可以认为JPanel正在发生鼠标移出事件。

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? 有什么更好的方法,哪个Java平台可以提供?

Have your class implement MouseListener and add it as a mouse listener on the outermost panel. 让您的类实现MouseListener并将其添加为最外面的面板上的鼠标侦听器。 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: 从JavaDoc:

void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. void mouseEntered(MouseEvent e)鼠标进入组件时调用。

void mouseExited(MouseEvent e) Invoked when the mouse exits a component. void mouseExited(MouseEvent e)鼠标退出组件时调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM