简体   繁体   中英

Java Swing Timer infinite loop

I'm having an issue with a simple Java swing Timer I set. It does everything fine up until having to stop. I think it is creating an infinite loop of timers upon timers but I've been following multiple tutorials and I can't see where I have gone wrong.

Code explanation: The runButtonListener needs to loop through as many times as filelinecount variable says (read from a different function). The code at the moment is just printing to the system, I will have it updating some animations later. filelinecount is 0 in the code below, but gets changed by a different function. So for the sake of debugging, I think the attached code is runnable if you change the value of filelinecount manually.

Any help is greatly appreciated

private int filelinecount = 0;
private int timercount = 0;
private Timer timer;

class runButtonListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e){

        // LOOK AT TIMER!!!
        if (timercount == filelinecount) {
            timer.stop();
            System.out.println("stopping");
            //timercount = 0;
        } else {
            System.out.println("yo " + timercount + "," + filelinecount);

            timercount++;
        }

        timer = new Timer(100,this);
        timer.start();
    }
}

Every time the timer calls you back you create a new timer and start it.

This includes after you call timer.stop() !

You need to only create the new timer if you want to continue.

Really you should look at another method for doing this rather than constantly recreating timers though. There are several methods available depending on your exact requirements.

For example using scheduleAtFixedRate , using a worker thread or SwingWorker , ScheduledExecutorService , etc.

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