2013-02-17 52 views
4

我想重复使用摆动计时器打印一个语句,但是语句没有打印!摆动计时器不起动

我在做什么错误?

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"); 
     }  
    } 
+1

滑稽如何[类似的问题(http://stackoverflow.com/q/14900697/203657)趋向在同一时间蠕动:-) – kleopatra 2013-02-17 13:20:01

回答

2

的javax.swing.Timer中可能开始为守护线程:它不保持JVM活着,你的主要目的,JVM退出。它将计时器事件发布到GUI事件队列中,该事件队列在第一个对话框或框架可见时开始。

如果您根本不需要窗口系统,则必须创建JFrame并使其可见或使用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 
    } 
} 
+0

我用java.util.Timer,它工作正常! 但我想问一下在非Gui应用程序中,我不能使用swing.Timer吗? – Snehasish 2013-02-17 11:21:08

+0

GUI具有事件队列和计时器事件在GUI事件队列上发布。 – Aubin 2013-02-17 12:16:59

2

javax.swing.Timer应该只使用Swing应用程序时使用。目前您的主要Thread正在退出,因为Timer使用守护进程Thread。作为一种变通方法,你可以这样做:

public static void main(String[] args) { 

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

非UI应用程序的另一种方法是使用ScheduledExecutorService

+0

我试过你的代码,但打印随机停止! 有时10秒后,有时4秒! – Snehasish 2013-02-17 11:18:48

+0

是的,你是对的! 我试过在timer.start()后调用Thread.sleep(50000),它工作! – Snehasish 2013-02-17 11:30:46

+0

我也在timer.start()之后试过这个,它也起作用了! long count = 0; for(long i = 0; i <1000000000; i ++) count ++; – Snehasish 2013-02-17 11:32:49