title: Why Timer does not work if we do not generate a window?
body: <p>Here is the code:</p>
  
  <pre><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();
    }
  }
  </code></pre>
  
  <p>It generates a window and then periodically prints "Hello World Timer" in the terminal (Command Prompt). If I comment this line <code>new JFrame().setVisible(true);</code> the application does not print anything to the command line. Why?</p>
  
  <p><strong>ADDED:</strong></p>
  
  <p>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?</p>
  
  <p><strong>ADDED 2:</strong></p>
  
  <p>The above described explanation still does not explain everything. For example, the program works if I comment the <code>new JFrame().setVisible(true);</code> and put <code>try {Thread.sleep(20000);} catch(InterruptedException e) {};</code> after the the <code>timer.start()</code>. 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 <code>new JFrame().setVisible(true);</code> 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?</p>