简体   繁体   中英

Why does java swing timer class not work?

Here is my main class

import javax.swing.Timer;

public class Test {
    public static int k=9;
    public static void main(String[] args) {
        
        Timer t = new Timer(100, new Loop());
        t.start();
    }  
}

And my class Loop which implements ActionListener

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Loop implements ActionListener {    
    @Override
    public void actionPerformed(ActionEvent e) {
       if(Test.k==9){
           System.out.println("Its's Working");
       } 
    }
    
}

I don't know why? When I've fully what it need but it doesn't print "Its's Working" in the console

And one more question is that "Is this Timer class similar to Thread in java ?"

Thanks for your answer!

Your program exits immediately after stating the timer, giving it no chance to fire.

The AWT Event Dispatch Thread (EDT) will need to have started for some reason in order for the timer to stay alive.

Swing is supposed to be use from this thread. If you do so, it should work.

    java.awt.EventQueue.invokeLater(() -> {     
        Timer t = new Timer(100, new Loop());
        t.start();
    });

To avoid indenting a lot of code , and to have a short main , I tend to create a method call go and use a method reference.

java.awt.EventQueue.invokeLater(Test::go);

private static void go() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM