简体   繁体   English

计时器延迟不起作用?

[英]Timer Delay Not Working?

I am trying to make this program print the current time in the console every second. 我试图使该程序每秒在控制台中显示当前时间。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import java.util.Date;

public class E10U27 extends JFrame {
    public static void main(String[] args){

   // Prep the listener to respond
   class TimerListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {

         Date now = new Date();
         System.out.println(now);
      }
   }

   ActionListener listener = new TimerListener();
   final int DELAY = 1000; 
   Timer t = new Timer(DELAY, listener);
   t.start();    
}
}

However, it prints like 50 of just a single time (ex. 2:52 50 times), and so on. 但是,它一次只能打印50张(例如2:52 50次),依此类推。 It does tick correctly though. 它确实正确打勾。 How to make it run correctly? 如何使其正确运行? Are there any mistakes in my code? 我的代码中有任何错误吗?

I ran the code without errors, but it finished without showing the date in the interval assigned to Timer, so I made some changes 我运行了代码,没有错误,但完成时未显示分配给Timer的时间间隔中的日期,因此我进行了一些更改

  1. Change the DELAY to 1000 (1 second) to print the current time every second 将DELAY更改为1000(1秒)以每秒打印当前时间

final int DELAY = 1000;

  1. Create the frame to make the program keep running, otherwise the main method will finish (new E10U27()).setVisible(true); 创建框架以使程序继续运行,否则主方法将完成(new E10U27()).setVisible(true);

This is the program with the modifications, it prints the current time every second: 这是经过修改的程序,它每秒打印一次当前时间:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import java.util.Date;

public class E10U27 extends JFrame {
    public static void main(String[] args){

        // Prep the listener to respond
        class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {

                Date now = new Date();
                System.out.println(now);
            }
        }

        ActionListener listener = new TimerListener();
        final int DELAY = 1000; // Milliseconds between timer ticks
        Timer t = new Timer(DELAY, listener);
        t.start();

        (new E10U27()).setVisible(true);
    }
}
final int DELAY = 999999;    
Timer timer = new Timer(DELAY, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    //Your Action    
    }
    });
    timer.start();

Refer the document here Java Docs 在此处参考文档Java Docs

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

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