简体   繁体   English

Swing计时器不启动

[英]Swing timer not Starting

I am trying to print a statement repeatedly using Swing Timer but the statement doesn't gets printed ! 我试图使用Swing Timer重复打印一个语句,但该语句不会被打印!

What's the mistake I am making ? 我犯的错是什么?

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;

    public class SwingTimer implements ActionListener {

        Timer timer;

        public static void main(String[] args) {
            SwingTimer obj = new SwingTimer();
            obj.create();
        }

        public void create() {
            timer = new Timer(1000, this);
            timer.setInitialDelay(0);
            timer.start();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Hello using Timer");
        }    
    }

The javax.swing.Timer probably starts as a daemon thread: it doesn't keep the jvm alive, your main ends, the jvm exits. javax.swing.Timer可能以守护程序线程开始:它不保持jvm活动,主要结束,jvm退出。 It post the timer events to the GUI event queue which starts when the first dialog or frame is made visible. 它将计时器事件发布到GUI事件队列,该队列在第一个对话框或框架可见时开始。

You have to create a JFrame, and make it visible or use the java.util.Timer if you don't need windowing system at all. 如果根本不需要窗口系统,则必须创建JFrame并使其可见或使用java.util.Timer

The following code shows how to use java.util.Timer : 以下代码显示了如何使用java.util.Timer

import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo extends TimerTask {

   private long time = System.currentTimeMillis();

   @Override public void run() {
      long elapsed = System.currentTimeMillis() - time;
      System.err.println( elapsed );
      time = System.currentTimeMillis();
   }

   public static void main( String[] args ) throws Exception {
      Timer t = new Timer( "My 100 ms Timer", true );
      t.schedule( new TimerDemo(), 0, 100 );
      Thread.sleep( 1000 );              // wait 1 seconde before terminating
   }
}

javax.swing.Timer should only be used when using Swing applications. 只有在使用Swing应用程序时才应使用javax.swing.Timer Currently your main Thread is exiting as the Timer uses a daemon Thread . 目前您的主Thread正在退出,因为Timer使用守护程序Thread As a workaround you could do: 作为一种解决方法,您可以:

public static void main(String[] args) {

   SwingTimer obj = new SwingTimer();
   obj.create();
   JOptionPane.showMessageDialog(null, "Timer Running - Click OK to end");
}

An alternative for non-UI applications is to use ScheduledExecutorService 非UI应用程序的替代方法是使用ScheduledExecutorService

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

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