Here is the code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TimerSample {
public static void main(String args[]) {
new JFrame().setVisible(true);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Hello World Timer");
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
}
It generates a window and then periodically prints "Hello World Timer" in the terminal (Command Prompt). If I comment this line new JFrame().setVisible(true);
the application does not print anything to the command line. Why?
ADDED:
I am not sure that I understand the answers correctly. As far as I understood, the timer starts a new thread. And this new thread exists simultaneously with the "main" thread. When the "main" thread is finished (when everything is done and there is nothing to do anymore) the whole application is terminated (together with the "new" thread created by the timer). Is right?
ADDED 2:
The above described explanation still does not explain everything. For example, the program works if I comment the new JFrame().setVisible(true);
and put try {Thread.sleep(20000);} catch(InterruptedException e) {};
after the the timer.start()
. So, I kind of understand that. With the sleep we keep the "main" thread busy so the thread created by the timer can exist. But new JFrame().setVisible(true);
do not occupy the "main". As far as I understand it creates its own thread (like Timer). So, why thread of the JFrame can exist without the main thread and thread of timer cannot?