如果鼠标正在移动,则重新启动计时器

Restart timer if mouse is moving

如果鼠标在 2 分钟内没有移动,我想重新启动我的程序。 我试图设置一个计时器并在每次鼠标移动时重新启动它,但到目前为止没有任何效果。 有人可以帮我解决这个问题吗?

frame.addMouseMotionListener(new MouseAdapter() {
        public void mouseMoved(MouseEvent e) {
            timer.cancel();
            timer.purge();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    frame.dispose();
                    try {
                        MyWeb neu = new MyWeb();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, 5000);
        }
    });

到目前为止,这是我的解决方案: 您可以创建自己的 Thread 休眠 2 秒。如果这段时间结束了,你可以做任何你想做的事。如果鼠标移动,您可以 interrupt Thread 并重复:

public class MyMouseMotionListener implements MouseMotionListener {

    private final Thread timerThread;

    public MyMouseMotionListener() {
        this.timerThread = new Thread(new SleeperThread());
        this.timerThread.start();
    }

    @Override
    public void mouseDragged(MouseEvent e) {}

    @Override
    public void mouseMoved(MouseEvent e) {
        this.timerThread.interrupt();
    }
}

和线程:

public class SleeperThread implements Runnable {

    @Override
    public void run() {
        while(true) {
            try{
                Thread.sleep(2000);
                System.out.println("Do Whatever you want.");
            } catch(InterruptedException ex) {
                System.out.println("Do nothing yet.");
            }
        }
    }

}

摇摆计时器

您想使用摇摆计时器 (javax.swing.Timer) rather than a common Timer (java.util.Timer). See the Oracle Tutorial.

自动穿线

Swing 计时器的特殊之处在于它会自动处理背景上的计时器滴答声,并且当最终触发时,计时器会自动处理 运行在 Swing 的主 GUI 线程上执行您的任务。所以你不必关心线程的细节。

永远不要在后台线程上访问 GUI 小部件非常非常 很重要。您 可能 侥幸逃脱,或者您可能会彻底破坏您的应用程序。发明 Swing Timer 是为了处理在后台线程上倒计时但切换回 GUI 线程以 运行 任务代码的琐事。

TimerTask 关闭您的应用程序

将您在计时器启动时要完成的工作写成 java.util.TimerTask

算法

Swing Timer 可以触发一次或重复触发。你想开火一次。触发后,关闭您的应用程序。

设置您的应用程序启动时的计时器。在您的应用程序中存储对该计时器的引用。为您想要的 2 分钟倒计时配置计时器。每次鼠标移动时,在 Swing Timer 上调用 restart。所以 2 分钟倒计时不断回到 2 分钟。您的应用可能会 运行 几个小时,2 分钟计时器会一遍又一遍地重置。

launch timer (2 mins) →  on mouse move  ↓ → timer fires → shutdown app
                      ↑ ← restart timer ←

关机与重启

当倒计时结束时,我不确定您是要关闭、重新启动,还是只是重新初始化应用程序中的某些状态。如果是最后一个(重新初始化状态),请将您的计时器设置为重复触发而不是一次触发。其余方法保持不变。

可能的优化

我不确定,但我怀疑在 每次 鼠标移动时重置计时器可能有点矫枉过正,并且可能会降低性能。个人资料自己看。如果确实需要大量成本,只需跟踪上次重置计时器的时间即可。要跟踪那个时刻,请使用 Instant object. Call Instant.now() to capture the current moment on every mouse movement. Calculate the elapsed time with Duration.between. When the duration exceeds an arbitrary limit, say 5 seconds, restart the Swing timer, and update the “when timer last restarted” Instant you store. Instant.now captures the current moment in a resolution of milliseconds in Java 8 and a resolution of microseconds in Java 9 and later. (An Instant actually holds nanoseconds,但传统计算机时钟不能 运行 那样好。)