Java – if we don’t generate windows, why doesn’t timer work?

This 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 periodically prints "Hello World timer" in the terminal (command prompt) If I comment on this line, the new JFrame () setVisible(true); The application does not print anything on the command line Why?

add to:

I'm not sure if I understand the answer correctly As far as I know, the timer starts a new thread And this new thread exists at the same time as the "main" thread When the "main" thread completes (when everything is complete and there is nothing to do), the entire application terminates (along with the "new" thread created by the timer) Is that right?

Add 2:

The above description still does not explain everything For example, if I comment on the new JFrame (), the program will work setVisible(true); And try {thread. Sleep (20000);} catch(InterruptedException e){}; In timer After start() So, I understand a little Using sleep, we keep the "main" thread busy so that the thread created by the timer can exist But the new JFrame () setVisible(true); Don't occupy the "main force" As far as I know, it creates its own thread (such as timer) So why can JFrame threads exist without main threads and timer threads?

Solution

You missed that Timer has nothing to do with the window you create. It works when you comment out the line created by the window

However, what you can't see is that your main program is in timer Exit after start (), so your program execution will terminate and enter the timer

If you add thread Sleep (20000), which can verify this; Finally (including the required exception handling), or any other code that takes some time Then your timer works normally, even if no window is created

The key is that the JFrame remains active even if nothing is displayed, which in turn keeps your timer active

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>