5 Replies Latest reply: Apr 5, 2009 2:10 PM by 807588 RSS

    Calendar getTime() counter (stopwatch) always starting from one hour

    user12076936
      Hello,

      I'm using the Calendar (from util) to run a simple stopwatch by calculating the time difference between the time the timer was started and the current time.
      I always get the counter to start from one however.

      Nevermind the session, you can replace it with the current time when start is called.
      package stopwatch;
      
      import java.text.SimpleDateFormat;
      import javax.swing.*;
      import java.awt.event.*;
      import java.util.Calendar;
      
      public class Counter implements ActionListener{
                long startTime;
                Timer timer;
                long elapsedTime;
                DateFormat time = new SimpleDateFormat("hh:mm:ss");
                long dayInMillis = 86400000;
                
           public Counter (Session parent){
                startTime = parent.startTime;
                timer = new Timer(1000,this);
                timer.start();
                Stopwatch.keyButton.setText("Pause");
           }
           public void resume(){
                timer = new Timer(1000,this);
                timer.start();
                Stopwatch.keyButton.setText("Pause");
           }
           public void freeze(){
                timer.stop(); //display should remain frozen at latest elapsedTime.
                Stopwatch.keyButton.setText("Resume");
                Stopwatch.counterDisplay.setText(time.format(elapsedTime));
           }
           public void reset(){
                timer.stop();
                elapsedTime = 0;
                Stopwatch.keyButton.setText("Start");
                Stopwatch.counterDisplay.setText(time.format(elapsedTime));
           }
           public void actionPerformed(ActionEvent e){
                if ((System.currentTimeMillis() - startTime) > 0) elapsedTime = (Calendar.getInstance()).getTimeInMillis() - startTime; 
                else elapsedTime = (dayInMillis - startTime) + (Calendar.getInstance()).getTimeInMillis();
                Stopwatch.counterDisplay.setText(time.format(elapsedTime));
           }
      }