基本上我想在用户完全不移动鼠标时移动它来运行方法。我不知道如何解决这个问题。
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class CustomMouseListener implements MouseMotionListener, MouseListener{
//whatever other methods I have (irrelevant for the question)
public void mouseMoved(MouseEvent e){
//code goes here
//but right now it fires every time the mouse is moved, which
//is way too much, I only need one per move
}
}
答案 0 :(得分:3)
普通算法
0. Fire mouse listener for every second with (x=x1, y=y1)
1. Store (x,y) of mouse pointer;
2. If (x,y) == (x1,y1) for another 15(or whatever you consider as time interval) sec
3. make account of (x1,y1);
4. Else do nothing;
5. If(x1,y1) changed after 15 sec
6. call mouseMove();
答案 1 :(得分:1)
这样做的一种方法是保存最后一次移动。如果当前时间 - lastMovedTime> x然后调用你的监听器或mouseStartedMoving()方法
public class CustomMouseListener实现MouseMotionListener,MouseListener { public final static long TIME_DIFFERNCE_FOR_IDLE = 800; //毫秒 long lastMoveTime = -1;
public void mouseMoved(MouseEvent e){
long currentTime = System.currentTimeMillis();
long diff = lastMoveTime - currentTime ;
if(lastMoveTime == -1 || diff > TIME_DIFFERNCE_FOR_IDLE ){
lastMoveTime();
}
lastMoveTime = System.currentTimeMillis();
}
}
void lastMoveTime(){
//do what u need to when mouse starts mooving
}
另一个需要添加轮询线程。可以创建一个大小为1的默认线程池。在run方法中调用一个任务(Runnable)1秒钟(或2或800毫秒 - 取决于你定义为移动之间的暂停)
无论如何,在原始代码中跟踪当前鼠标位置x,y并暴露给runnable。
runnable跟踪前一个鼠标位置。 Runnable中还有一个状态变量,它是一个枚举 - {INITIAL,STATIONARY,MOVING}。
最初是INITIAL,如果你获得鼠标移动位置,它的INITIAL就会移动到 如果MOVING和Runnable中的X滴答,它不会移动到STATIONARY。再次在鼠标移动中,它将移至MOVING。 当它从INITIAL移动到MOVING OR STATIONARY到MOVING时,可以有被调用的监听器或者只是一个特殊的方法 - mouseStartedMoving() 在那里做任何事情。
答案 2 :(得分:1)
如果您只想知道两件事情,当鼠标开始移动时以及当鼠标停止移动时,您可以使用javax.swing.Timer
在事件之间插入延迟,这样它才会被触发当达到延迟时......
public class CustomMouseListener implements MouseMotionListener, MouseListener{
private javax.swing.Timer moveTimer;
private boolean moving = false;
public CustomMouseListener() {
moveTimer = new javax.swing.Timer(25, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
moving = false;
// Method to be called when you want to
// to know when the mouse has stopped moving...
}
});
moveTimer.setRepeats(false);
}
//whatever other methods I have (irrelevant for the question)
public void mouseMoved(MouseEvent e){
if (moving || moveTimer.isRunning()) {
moveTimer.restart();
} else {
moving = true;
moveTimer.start();
// Method to call when you want to know when the mouse
// has started moving...
}
}
}
基本上,如果在没有调用mouseMoved
的情况下经过25毫秒,javax.swing.Timer
将会被触发....你可能想稍微使用这个阈值......