Hello, I have a school assignment to build a 2 minute countdown timer in java. Gunjannigam managed to assist me in creating the functions. My code for secondCount, I have built a function so that I can adjust secondCount to a number and it will change the timer. When secondCount is at 25, the timer is displayed as 00:15:000 in mm:ss:sss format. When secondCount is at 200, the timer is displayed as 02:00:000 in mm:ss:sss format.

However, the problem i am having is when the timer counts down to zero. at 00:00:000, the timer instantly resets to 59:59:000 and continues to count down from there. How would i go about fixing my code so that i can get the timer to stop when it gets to zero instead of continuing. In the final product of this program, it is my goal to get it to play a buzzer sound so it can act as a sports timer.

...forgive me, i am a very new programmer to java ( about two months of java practise )

//***************Import java files necessary for this project********************//
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
//*********************************************************************//
public class Stopwatch extends JFrame implements ActionListener, Runnable
{
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss : SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
     {
         public void run()
         {
             displayElapsedTime(Stopwatch.this.startTime - System.currentTimeMillis());
         }
     };
//************************Action Performed Function***********************//
     public void actionPerformed(ActionEvent ae)
     {
         if(isRunning)
         {
             long elapsed= startTime - System.currentTimeMillis() ;
             
             isRunning= false;
             try
             {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
         {
  //*********************Start Command for the Function*********************//
  /*
   * Here I have built a function so that I can adjust secondCount to a number
   * and it will change the timer. When secondCount is at 25, the timer is displayed as 
   * 00:15:000 in mm:ss:sss format. When secondCount is at 200, the timer is displayed 
   * as 02:00:000 in mm:ss:sss format. 
  */
 			// (25/15)=1.66
  			int secondCount = 200; //integer must be a multiple of 25
			long timeAdjust = (6200-(secondCount))*60*10;
           		startTime= 2*60*1000+System.currentTimeMillis()-timeAdjust;
           		isRunning = true;
           		updater= new Thread(this);
           		updater.start();
 //***********************************************************************//
      	}
	}
//*********************Action Performed Function Ends**********************//  
//**************************Display Time Function**************************//
      private void displayElapsedTime(long elapsedTime)
      {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
      }
  //***********************Display Time Function Ends***********************//
  //**********************Function to Run the Timer*************************//
     public void run()
     {
         try
         {
             while(isRunning)
             {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
         {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
 //************************Function to Run Timer Ends************************//
 //**********************Create the StartStop Button*************************//
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
//********************Create the StartStop Button Ends***********************//     

	public static void main(String[] arg)
 	{
         new Stopwatch().addWindowListener(new WindowAdapter()
          {
             public void windowClosing(WindowEvent e)
             {
                 System.exit(0);
             }
         });
     }
}

Hello, I have a school assignment to build a 2 minute countdown timer in java. Gunjannigam managed to assist me in creating the functions. My code for secondCount, I have built a function so that I can adjust secondCount to a number and it will change the timer. When secondCount is at 25, the timer is displayed as 00:15:000 in mm:ss:sss format. When secondCount is at 200, the timer is displayed as 02:00:000 in mm:ss:sss format.

However, the problem i am having is when the timer counts down to zero. at 00:00:000, the timer instantly resets to 59:59:000 and continues to count down from there. How would i go about fixing my code so that i can get the timer to stop when it gets to zero instead of continuing. In the final product of this program, it is my goal to get it to play a buzzer sound so it can act as a sports timer.

...forgive me, i am a very new programmer to java ( about two months of java practise )

//***************Import java files necessary for this project********************//
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
//*********************************************************************//
public class Stopwatch extends JFrame implements ActionListener, Runnable
{
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss : SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
     {
         public void run()
         {
             displayElapsedTime(Stopwatch.this.startTime - System.currentTimeMillis());
         }
     };
//************************Action Performed Function***********************//
     public void actionPerformed(ActionEvent ae)
     {
         if(isRunning)
         {
             long elapsed= startTime - System.currentTimeMillis() ;
             
             isRunning= false;
             try
             {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
         {
  //*********************Start Command for the Function*********************//
  /*
   * Here I have built a function so that I can adjust secondCount to a number
   * and it will change the timer. When secondCount is at 25, the timer is displayed as 
   * 00:15:000 in mm:ss:sss format. When secondCount is at 200, the timer is displayed 
   * as 02:00:000 in mm:ss:sss format. 
  */
 			// (25/15)=1.66
  			int secondCount = 200; //integer must be a multiple of 25
			long timeAdjust = (6200-(secondCount))*60*10;
           		startTime= 2*60*1000+System.currentTimeMillis()-timeAdjust;
           		isRunning = true;
           		updater= new Thread(this);
           		updater.start();
 //***********************************************************************//
      	}
	}
//*********************Action Performed Function Ends**********************//  
//**************************Display Time Function**************************//
      private void displayElapsedTime(long elapsedTime)
      {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
      }
  //***********************Display Time Function Ends***********************//
  //**********************Function to Run the Timer*************************//
     public void run()
     {
         try
         {
             while(isRunning)
             {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
         {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
 //************************Function to Run Timer Ends************************//
 //**********************Create the StartStop Button*************************//
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
//********************Create the StartStop Button Ends***********************//     

	public static void main(String[] arg)
 	{
         new Stopwatch().addWindowListener(new WindowAdapter()
          {
             public void windowClosing(WindowEvent e)
             {
                 System.exit(0);
             }
         });
     }
}

You have to pass 0 time to display so your time stops at zero
For this u have to adjust your make your timeAdjust variable global/public and calculate it before starting the thread (Your timeAdjust will be a constant value).
Now in your Thread.run() method change Line

displayElapsedTime(Stopwatch.this.startTime - System.currentTimeMillis());

to

displayElapsedTime(Math.max(Stopwatch.this.startTime - System.currentTimeMillis(),-timeAdjust));// my timeAdjust as I already told is 30*60*1000 for 30 minutes

I hope this will work

You have to pass 0 time to display so your time stops at zero
For this u have to adjust your make your timeAdjust variable global/public and calculate it before starting the thread (Your timeAdjust will be a constant value).

I brought out the timeAdjust function like u said and my one error was fixed.

// (25/15)=1.66
int secondCount = 25; //integer must be a multiple of 25
public long timeAdjust = (6200-(secondCount))*60*10;

It works and it stops at zero. Thanks so much for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.