当前位置: 代码迷 >> Java相关 >> 请教关于Timer的问题
  详细解决方案

请教关于Timer的问题

热度:379   发布时间:2008-04-20 23:28:58.0
请教关于Timer的问题
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class InnerClassTest{
    public static void main(String[] args){

             ActionListener taskPerformer = new ActionListener() {
                 public void actionPerformed(ActionEvent evt) {

                    Date now = new Date();
          System.out.println("At the tone,thi time is "+now);
          Toolkit.getDefaultToolkit();
                 }
             };
            new Timer(delay, taskPerformer).start();
            JOptionPane.showConfirmDialog(null,"Quit program?");
      System.exit(0);
      }
}
在上面程序中,为什么只有有“ JOptionPane.showConfirmDialog(null,"Quit program?"); ”这一句运行后才能打印时间?
能否改成直接在DOS里就打印出时间来,而不是像上面那样弹出个窗口后才能打印时间的。
谢谢
搜索更多相关的解决方案: Timer  

----------------解决方案--------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class InnerClassTest{
    public InnerClassTest()
    {
         ActionListener taskPerformer = new ActionListener() {
                 public void actionPerformed(ActionEvent evt) {
            System.out.println("www.it.com.cn 1");
                    Date now = new Date();
              System.out.println("At the tone,thi time is "+now);
                  //Toolkit.getDefaultToolkit();
                 }
             };
            Timer timer =  new Timer(1000, taskPerformer);
         
        timer.start();
       
            System.out.println("www.it.com.cn 2");
        try{
            Thread.sleep(5000); //选让主线程暂停一下,然后让Timer线程有机会注册及运行的ActionListener方法。
        }catch(Exception e)
        {
            System.out.println("error");
        }
    }
    public static void main(String[] args){

        new InnerClassTest();
      }
}
----------------解决方案--------------------------------------------------------
谢谢
另外,可能说明下原因吗
----------------解决方案--------------------------------------------------------
回复 3# 的帖子
使用Timer会另外开启一个线程,而主线程继续运行自己的。
----------------解决方案--------------------------------------------------------
  相关解决方案