title: Java Timer object error: Timer already cancelled
body: <p>I have a JButton that starts a countdown timer when pressed. When I press the button, it begins, and when I press it again (Button will say "Stop"), it stops. However when I press it again to start the time again I get an error saying: </p>
  
  <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled.
  </code></pre>
  
  <p>Here is my code: </p>
  
  <pre><code>    final static Timer t = new Timer();
  
      static void startTimer(JButton b) {
  
           t = new Timer(); // Solved: I needed to create a new Timer object.
  
           t.scheduleAtFixedRate(new TimerTask() { 
  
              double timeleft = calcShutterSpeed;
  
              @Override
              public void run() {
                  String s = secondsToMinutes(timeleft);
                  time.setText(s);
                  timeleft--;
                  if (timeleft &lt; 0) {
                      t.cancel();
                      b.setText("START TIMER");
                      b.setForeground(Color.BLACK);
                  }
              }
          }, 0, 1000);
      }
  
      static void stopTimer() {
          t.cancel();
      }
  
      /**
       * Creates the timer if "Start" is pressed.
       * 
       * @param b
       */
      static void timer(JButton b) {
          b.addActionListener(new ActionListener() {
  
              @Override
              public void actionPerformed(ActionEvent e) {
  
                  // If start button is pressed, change text to display stop
                  if (b.getText() == "START TIMER") {
                      startTimer(b);
                      b.setText("STOP TIMER");
                      b.setForeground(Color.RED);
                  }
                  // If stop button is pressed, cancel timer and change text to start
                  else if (b.getText() == "STOP TIMER") {
                      stopTimer();
                      b.setText("START TIMER");
                      b.setForeground(Color.BLACK);
                  }
              }
          });
      }
  </code></pre>
  
  <p>Any tips or suggestions that can fix this problem would be much appreciated. Thanks in advance!</p>
  
  <p>EDIT: Really really simple fix for the curious. The fix is in the code.</p>