title: Use javax.swing.Timer to make countdown timer in Java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/14391299/stop-timer-with-conditional-only-works-first-time">Stop timer with conditional only works first time?</a>  </p>
  </blockquote>
  
  
  
  <p>I'm very confused as to how to make a timer using the swing and not util timer.</p>
  
  <p>I am making a game where users have to answer questions in a 30 second time limit. I have a PlayFrame, where the time is shown, and a method inside PlayFrame called startTimer which contains all the timer stuff.</p>
  
  <pre><code>public static void startTimer() {
  
      int elapsedSeconds = 0;
      javax.swing.Timer myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
      elapsedSeconds++;
  
      if (elapsedSeconds == 30) {
          myTimer.stop();
          timerLabel.setText("0");
          wrong();
      } else {
          String text = String.format("f", 30 - elapsedSeconds);
          timerLabel.setText(text);
      }
  
      if (myTimer != null &amp;&amp; myTimer.isRunning()) {
          myTimer.stop();
          myTimer = null;
          timerLabel.setText("0");
      } else {
          elapsedSeconds = 0;
          myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
          myTimer.start();
          String text = String.format("t", 30);
          timerLabel.setText(text);
      }
  }
  </code></pre>
  
  <p>What I want this method to do is have a timer that counts down from 30 until the question is answered correctly. If the answer is answered incorrectly I want the timer to stop.</p>
  
  <p>For an answer perhaps some psuedocode (or real code) to move me in the right direction. And this is for personal use, not homework or anything.</p>
  
  <p>Please remember that this is a part of my whole code and it needs to work with other parts of it. I'll give more information upon request, thanks!</p>
  
  <p>EDIT: New startTimer() method <em>NOTE</em> all System.out.print is for testing only:</p>
  
  <pre><code>  public static void startTimer() {
      class TimerListener implements ActionListener {
          Timer timer = new Timer(1000, new TimerListener());
          int elapsedSeconds = 30;
          String seconds = Integer.toString(elapsedSeconds);
  
          @Override
          public void actionPerformed(ActionEvent evt) {
              timer.start();
              if (elapsedSeconds == 0) {
                  //System.out.print("here");
                  timer.stop();
                  PlayFrame.wrong();
              }
              else{
                  //System.out.print("hersfde");
                  elapsedSeconds--;
              PlayFrame.timerLabel.setText(seconds);
              }
              //System.out.println(elapsedSeconds);
          }
      }
      //System.out.print("l");
  }
  </code></pre>
  
  <p>Doesn't do anything and not sure why.</p>