0

I'm trying to create a 1 hour countdown timer. I'm using a label and a button. When i press the start button the countdown should start but instead of that my window freezes. I searched in many sites and they said that the problem is the Thread.sleep(1000) but i didn't get a clear answer on how i can fix my problem!

        btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            label.setText("60:00");
            for(int i=59;i>=0;i--)
            {
                for(int j=59;j>=0;j--){
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    if(i<10 && j<10){
                        label.setText("0"+i+":0"+j);
                    }
                    else if(i<10 && j>=10){
                        label.setText("0"+i+":"+j);                 
                    }
                    else if(i>=10 && j<10){
                        label.setText(i+":0"+j);                
                    }
                    else {
                        label.setText(i+":"+j);             
                    }
                }
            }
        }
    });
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 3
    First look at [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for the reason why you're having issues, then have a look at [How to use Swing Timers](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for probably the suitable solution – MadProgrammer Feb 07 '18 at 23:17
  • [Here](https://stackoverflow.com/questions/45610774/i-cant-see-circle-moving/45621978#45621978) and [here](https://stackoverflow.com/questions/34746795/creating-an-animated-4x4-grid-in-java/34748083#34748083) you can find two (extra) good examples that use `Swing Timer` as suggested above by @MadProgrammer – Frakcool Feb 07 '18 at 23:21
  • @Frakcool I don't know if you can or not, but you can add them to the "duplicate answers" list - assuming you can see a nice "edit" button the listed duplicates ;) – MadProgrammer Feb 07 '18 at 23:24
  • @MadProgrammer I'm afraid I can't do that (yet) it's only reserved for a *shiny, gold tag badge* user, I can just suggest it on the comments by now :) – Frakcool Feb 07 '18 at 23:25
  • @Frakcool Added the first one. – chrylis -cautiouslyoptimistic- Feb 07 '18 at 23:59
  • @chrylis cool thanks :) – Frakcool Feb 08 '18 at 00:00

0 Answers0