我试图让这个程序每秒在控制台中打印当前时间。
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();
}
}
然而,它只打印了50次(例如2:52 50次),依此类推。它虽然确实正确。如何让它正确运行?我的代码中有错误吗?
答案 0 :(得分:1)
我没有错误地运行代码,但是在没有在分配给Timer的时间间隔中显示日期的情况下完成了,所以我做了一些更改
final int DELAY = 1000;
(new E10U27()).setVisible(true);
这是带有修改的程序,它每秒打印当前时间:
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);
}
}
答案 1 :(得分:-1)
final int DELAY = 999999;
Timer timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Your Action
}
});
timer.start();
请参阅此处的文件Java Docs