Recurring Countdown Timer in Java

前端 未结 4 1079
自闭症患者
自闭症患者 2021-01-21 21:49

I\'m trying to implement a countdown timer into a pre-existing public class and I have a few questions.

An overview: I want to have a timer within a program that counts

4条回答
  •  半阙折子戏
    2021-01-21 22:26

    If you need to update your GUI better to use SwingWorker http://en.wikipedia.org/wiki/SwingWorker I would write something like this:

    SwingWorker timer = new SwingWorker() {
        Integer timer=60;
        @Override
        protected String doInBackground() throws Exception {
          //update guiModel
          //label.setText(timer.toString());
            while(timer>0){
            Thread.sleep(1000);
            timer--;
            }
            return null;
        }
        @Override
         public void done(){
             System.exit(0);
         } 
    };
    
    JButton restart = new JButton(){
        {
      addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    timer.cancel(true);
                    timer.execute();
                }
            });      
        }
    };
    

提交回复
热议问题