How to handle Timers correctly in Java?

2020-04-11 07:31发布

I want my timer to execute the actionPerformed method only one time once it 5 seconds the time but it is writing in the console "Hello" lots of times:

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

import javax.swing.Timer;

public class X{
    public static void main(String args[]) {

        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println( "Hello" );
            }
        };
        Timer timer = new Timer( 5000, actionListener );
        timer.start();
    }
}

How can I make the effect I want? Thanks

5条回答
【Aperson】
2楼-- · 2020-04-11 08:01

Don't neglect to use the event dispatch thread. There's nothing wrong with java.util.Timer, but javax.swing.Timer has several advantages with Swing.

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

import javax.swing.Timer;

public class X {

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ActionListener actionListener = new ActionListener() {

                    public void actionPerformed(ActionEvent actionEvent) {
                        System.out.println("Hello");
                    }
                };
                Timer timer = new Timer(5000, actionListener);
                timer.start();
            }
        });
    }
}

If using java.util.Timer, update the GUI using a continuation.

查看更多
何必那么认真
3楼-- · 2020-04-11 08:03
class MyTask extends TimerTask {
    public void run() {
      System.out.println("Hello");

    }
  }

and then

timer = new Timer();
timer.schedule(new MyTask(), 5000);
查看更多
家丑人穷心不美
4楼-- · 2020-04-11 08:17

Sounds like you want a java.util.Timer rather than a javax.swing.Timer.

查看更多
Anthone
5楼-- · 2020-04-11 08:20

This should do the trick!

new JFrame().setVisible(true);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-04-11 08:27

As already mentioned, it's better to use java.util.Timer, but you can also use setRepeats() before starting:

timer.setRepeats(false);
查看更多
登录 后发表回答