[英]How to have a MouseMove event fire only if the mouse is hovered over an element for at least a specific amount of time?
当用户将鼠标指针移动到JPanel
的某个区域上并稍微延迟时,我想显示一个JFrame
。 我通过将MouseAdapter
附加到JPanel
并覆盖MouseMove
方法来显示JFrame
。
addMouseListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
Point p= e.getLocationOnScreen();
//check if Point p is within the boundaries of a rectangle.
//show a JFrame
}
});
为了获得延迟,我认为我应该使用类似Thread
的东西,使用sleep
,条件是如果鼠标移出边界必须中断,但我不确定这是最好的方法。 目前,我只看到与JavaScript相关的SO问题。 在Java中最好的方法是什么?
您可以使用MouseAdapter
类中的mouseEntered
和mouseExited
事件。
您可以在mouseEntered
方法上设置计时器,并检查在对象上花费的时间是否>=
mouseExited
方法中的指定时间,如果是,则执行操作。
对于鼠标停留在同一点的情况,您可以使用Timer
延迟所需的秒数,并在mouseExited
处设置处理程序,以便在指定时间之前退出指针时停止计时器。
也许一个好的解决方案是使用java.util.Timer
。
addMouseListener(new MouseAdapter() {
private int delay = 1000;//1 second
private Timer timer = null;
private int startTime =0;
@Override
public void mouseMoved(MouseEvent e) {
Point p= e.getLocationOnScreen();
boolean pointInArea=false;
//check if Point p is within the boundaries of a rectangle.
if(pointInArea){
//A JFrame is queued to be shown
if(System.currentTimeMillis()-startTime>delay){
//A JFrame has been already shown, then show a new one
startTime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run() {
//LAUNCH JFrame
}
}, delay);
}
}
else (!pointInArea && timer != null){
timer.cancel();
timer = null;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.