简体   繁体   中英

Having Issues With Java Swing Timer and Infinite Loops

I am having an issue with a piece of my code in Java, it seems to be creating an endless loop.

public void progress(){
    x = 3;

    timer = new Timer(800, new ActionListener() {
            public void actionPerformed(ActionEvent evt){
                System.out.println(x);
                x--;

                if(x < 1){
                    UI();
                    timer.stop();
                }
            }
        });

    timer.start();
}

The method UI asks for input via SavitchIn, and it doesn't seem to run the line. I print before I ask for input in the UI method, and the print works just fine. When I remove this timer from my code, and keep the UI method the same, it works fine. Prints and then takes input. I've added a timer.stop() in UI method as well, and I am positive the timer is stopped, however after running the program I am forced to Reset the Virtual Machine the next time around otherwise it wont run. Any help is appreciated!

Your UI() method likely should be called on a background thread as it is likely tying up the Swing event thread (this we have to guess since you don't show it). So create a SwingWorker or a background thread and do this call in there. For more on this, please read Concurrency in Swing .

eg,

public void progress() {
  x = 3;

  timer = new Timer(800, new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
        System.out.println(x);
        x--;

        if (x < 1) {
           new Thread(new Runnable() {
              public void run() {
                 UI();
              }
           }).start();
           timer.stop();
        }
     }
  });

  timer.start();
}

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