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. 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
final int DELAY = 1000;
(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);
}
}