且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何停止 Javax.Swing.timer?

更新时间:2023-12-03 23:32:52

你应该改变:

            c++;
            Action.setText(ActionName.get(c)); //move this down
            if(c>=ActionTime.size()){
                timer.stop();
                JOptionPane.showMessageDialog(null, "Workout Completed!");
            }

到:

            c++;
            if(c>=ActionTime.size()){
                timer.stop();
                JOptionPane.showMessageDialog(null, "Workout Completed!");
                return; //add this too as the program should not continue with below
            }
            Action.setText(ActionName.get(c)); //to here

因为当您尝试执行 ActionName.get(c)c 的值超过可能的最大值,get 方法将抛出 Exception.这导致我们犯了第二个错误:

Because when you attempt to do ActionName.get(c) when the value of c exceeds the maximum possible value, the get method will throw an Exception. That leads us to the second mistake you're making:

           catch(Exception error2){

           }

这样做会使程序忽略Exception 并继续像什么也没发生一样.一个容易犯的错误,使您误以为其他事情是错误的,但现在您知道了!改为:

Doing this makes the program ignore the Exception and continue as though nothing happened. An easy-to-make mistake that deceived you into thinking something else is wrong, but now you know! Change it to:

           catch(Exception error2){
                error2.printStackTrace();
                System.exit(-1); //or some error handling
           }

或者删除 try/catch 块,以便 Exception 将结束您的程序或以其他方式处理.

Or remove the try/catch block so that the Exception will end your program or is handled some other way.