【问题标题】:Java Swing TimerJava 摆动计时器
【发布时间】:2021-01-16 08:27:15
【问题描述】:
ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //...Perform a task...

        logger.finest("Reading SMTP Info.");
    }
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(false);
timer.start();

根据文档,这个计时器应该触发一次,但它永远不会触发。 我需要它触发一次。

【问题讨论】:

    标签: java swing timer


    【解决方案1】:

    这个简单的程序适合我:

    import java.awt.event.*;
    import javax.swing.*;
    
    public class Test {
        public static void main(String [] args) throws Exception{
            ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    //...Perform a task...
    
                    System.out.println("Reading SMTP Info.");
                }
            };
            Timer timer = new Timer(100 ,taskPerformer);
            timer.setRepeats(false);
            timer.start();
    
            Thread.sleep(5000);
        }
    }
    

    【讨论】:

    • 谢谢,我发现我的问题记录器在运行此代码后被初始化,这就是为什么我从来没有看到我的测试消息。使用 println 切换记录器有帮助。
    • IIRC,你不应该在 EDT 之外使用 javax.swing.Timer。
    • 我想我现在爱你! :D 非常感谢!
    • 这个答案表明主线程在计时器完成之前完成。由于主线程是特殊的,所有其他非守护线程也将在 main() 终止时终止。为避免这种情况(不使用守护线程),您应该获取对计时器线程的引用,并在 main() 中调用 <timer thread object>.join();
    【解决方案2】:

    这个程序可以正常工作...

    setRepeats(boolean flag)函数用于设置重复调用function(actionPerformed)或者只调用一次

    1. timer.setRepeats(false) == timer只调用一次actionperformed方法
    2. timer.setRepeats(true) == timer按指定时间重复调用actionPerformed方法

    摇摆计时器工作

    1. 一次性完成任务
    2. 重复执行任务

    创建摇摆计时器的步骤:

    1. 创建动作监听器
    2. 创建计时器构造函数,然后在其中传递时间和 actionlistener
    3. 实现执行任务的actionPerformed() 函数
    4. 使用timer.start()在定时器构造函数指定的时间之间启动任务,使用timer.stop()停止任务

    例子:

    ActionListener al=new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            //do your task
            if(work done)
                timer.stop();//stop the task after do the work
        }
    };
    Timer timer=new Timer(1000,al);//create the timer which calls the actionperformed method for every 1000 millisecond(1 second=1000 millisecond)
    timer.start();//start the task
    

    【讨论】:

    • 嘿,你的语法有点错误,但我喜欢简单的 sn-p ActionListener al=new ActionListener(){//code}; 是正确的,而不是 ActionListener al=new ActionListener({//code});
    【解决方案3】:

    您的任务可能只需要在事件线程 (EDT) 上报告结果,但在后台线程中以某种周期性频率执行实际工作。

    ScheduledExecutorService 正是你想要的。请记住通过 SwingUtility.invokeLater(...) 在 EDT 上更新 UI 的状态

    【讨论】:

      【解决方案4】:

      我从日志语句中猜测您正在执行某种 SMTP 操作。我认为java.swing.Timer 用于与 UI 相关的定时操作是正确的,因此它为什么需要和 EDT 运行。对于更一般的操作,您应该使用java.util.Timer

      本文链接自 JavaDocs - http://java.sun.com/products/jfc/tsc/articles/timer/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多