简体   繁体   中英

Swing Timer Not Working (Java)

For some reason even though I am using the exact code example from oracle's website for the Swing Timer it is not waiting for 1 second. It just skips to the JOptionPane that says "Your score was etc etc".

Here is my source code for a school project. Why is this not working and not waiting for 1 second before running the rest of the code?

//Check to see if user has enetered anything
if(!answered)
{
    int delay = 1000; //milliseconds
    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //...Perform a task...
        }
    };
    new Timer(delay, taskPerformer).start();
    afk = true;
    incorrect += 1;
    answered = true; //This breakes it out of the loop
}

A timer is used to run a callback after a specific amount of time. If you simply want to delay, you can either move the code to be run after the delay into the taskPerformer action listener.

Thread.sleep(1000) is not ideal here, because it will cause the UI to completely freeze as you will make the UI thread sleep.

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