Java Swing: Change Text after delay

后端 未结 3 1460
一向
一向 2020-12-06 23:08

Basically, I have this game where once guesses the correct answer it starts a new game with a new word. I want to display Correct! but after three seconds, chan

相关标签:
3条回答
  • 2020-12-06 23:20

    it works after 3 seconds..

    ActionListener taskPerformer = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                statusbar.setText("Status");
            }
        };
        Timer timer = new Timer(3000, taskPerformer);
        timer.setRepeats(false);
        timer.start();
    
    0 讨论(0)
  • 2020-12-06 23:23

    if these piece of code is in the event handlers, then you are holding up the UI thread, and it is not going to work as UI update will only happens after you finished your work in the event handlers.

    You should create another thread do the work of "sleep 3 second, and change the text field, and trigger repaint". Using Timer or similar utilities is the easiest way to achieve what I am describing.

    0 讨论(0)
  • 2020-12-06 23:35

    Swing is an event driven environment. While you block the Event Dispatching Thread, no new events can be processed.

    You should never block the EDT with any time consuming process (such as I/O, loops or Thread#sleep for example).

    You might like to have a read through The Event Dispatch Thread for more information.

    Instead, you should use a javax.swing.Timer. It will trigger a ActionListener after a given delay.

    The benefit of which is that the actionPerformed method is executed with the context of the Event Dispatching Thread.

    Check out this or this or this or this for an examples

    0 讨论(0)
提交回复
热议问题