Avatar of sargent240
sargent240
Flag for United States of America asked on

Countdown timer

I have code for a countdown timer I am trying to make work as a clock on a basketball scoreboard.  When I do c.start() the timer starts counting down and when I do c.stop() it stops.  The problem is when I do c.start() to start it up again I need it to continue counting down from where it was when I stopped it.  It just hangs up and that is it.  What do I need to do?  I am using Linux.  Thanks.



        public class CountDownThread  extends Thread implements ActionListener {
            private volatile int hour;
            private volatile int min;
            private volatile int seconds;
            private volatile long count;
            private volatile int i;
            private volatile DateFormat df;
            private volatile javax.swing.Timer t;
            private Object javax;

            public CountDownThread( int h, int m, int s ) {
                hour = s;
                min = m;
                seconds = s;
                count = 0;              
                t = new javax.swing.Timer(1000, this);
            }
           
            @Override
            public void run() {

      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, min);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();
        }


     public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC
         
       if (clockRunning == 1) {
          if (t.isRunning()) {
              t.stop();
              clockRunning = 0;
          } else {
              t.start();
          }
      } else {
        tfTime.setText(df.format(count));
        if(df.format(count).equals("00:00:00"))
          t.stop();
        count -= 1000;
      }
    }
           
    }
JavaProgramming

Avatar of undefined
Last Comment
CEHJ

8/22/2022 - Mon
CEHJ

There's some confusion here. Your class should not extend Thread - a Timer already has a Thread with which you shouldn't interfere. Your class only needs to implement ActionListener, in the actionPerformed of which should really only be the code that stops the Timer when it reaches zero. Remove all the volatile modifiers as they are (almost certainly) unnecessary
hour = s;

Open in new window

is wrong btw. You should adhere to best practice and use
this.hour = hour;

Open in new window

then you won't make that kind of error. Are you sure that's the code you're running btw?
sargent240

ASKER
Do I just remove the "extends Thread" from the class declaration?  I'm still trying to get wrapped around the class thing and threads.
sargent240

ASKER
I would like to be able to start and stop the timer even though the time is not zeros.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
CEHJ

Do I just remove the "extends Thread" from the class declaration?
Yes that's a start. Remove the run method too

I would like to be able to start and stop the timer even though the time is not zeros.
You can, but that would not generally be done from the actionPerformed method. You'd do that by exposing the Timer methods to the caller
sargent240

ASKER
Below is another timer class I have.  When I put in the following line it starts but I need a hand with the code that will stop and start it so it picks up where it left off.  I start it with "CountDownTimer c = new CountDownTimer(0, 8, 0);".  


       
    public class CountDownTimer implements ActionListener {
    private long count;
    private DateFormat df;
    private javax.swing.Timer t;

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();

    }
    public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC
      tfTime.setText(df.format(count));

      if(df.format(count).equals("00:00:00"))
          t.stop();
      count -= 1000;
    }
}
sargent240

ASKER
Can I somehow pause the time and tell it to resume using the "clockRunning" variable I have in the actionPerformed method?  I tried what is listed below and it did not work.

       
    public class CountDownTimer implements ActionListener {
    private long count;
    private DateFormat df;
    private javax.swing.Timer t;

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();


    }

    public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC        
        if (clockRunning == 0) {
            t.start();
            clockRunning = -1;
        }
        if (clockRunning == 1) {
            t.stop();
            clockRunning = -1;
        }
       
      tfTime.setText(df.format(count));

      if(df.format(count).equals("00:00:00"))
          t.stop();
      count -= 1000;
    }
}
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CEHJ

I've already told you what you need to do to control the stopping/starting of the clock HERE Please use [ code ] tags for any future code posts
krakatoa

I already gave you a solution to this. Which was evidently ignored.
sargent240

ASKER
Well, if you are referring to the following:

You can, but that would not generally be done from the actionPerformed method. You'd do that by exposing the Timer methods to the caller


I would equate the above response, if this is the one you are referring to, to someone from Europe landing in New York, asking directions to Salt Lake City and someone telling the "Go West."  Can you be a little more explicit?  I am now using the code posted in 38729602.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
krakatoa

lol. What are you on . . .?
sargent240

ASKER
I don't understand your post krakatoa.
krakatoa

Q.E.D. ;) Bye. G'luck.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
sargent240

ASKER
krakatoa - Your solution was not useful.  I cannot control the timer with buttons and as I read the code you posted the other day it requires buttons and I do not have that luxury.  If you have read the previous info I posted you will not the timer must be controlled by another computer sending start and stop commands over a lan.
krakatoa

I am not assisting on this or other questions in your case as there is no point offering you comments which you obviously know better than to ask. In your previous question, you have to ask yourself why you then chose valeri's answer, which not only does not compile out of the box, but encapsulates a button in its answer.

When you decide to acknowledge people's help on the forum with a bit more dignity and appreciation, then it might help your cause. In the meantime, I'm out.
sargent240

ASKER
Have a nice day
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
CEHJ

I would equate the above response, if this is the one you are referring to, to someone from Europe landing in New York, asking directions to Salt Lake City and someone telling the "Go West."
I don't actually accept that* but let's say for the sake of argument i do accept it.
I am now using the code posted in 38729602.
So i told you to go west yet you decided to stay rooted to the spot - since the code is materially no different? Was that because you didn't know what 'go west' meant or that you didn't consider it to be in enough detail? Either way, what you should have done is not to post essentially the same code, but to ask for clarification.
If you have read the previous info I posted you will not the timer must be controlled by another computer sending start and stop commands over a lan.
Why didn't you see fit to give that as a requirement in this question?

http://technojeeves.com/joomla/index.php/free/117-smart-questions

* (since the instructions are actually precise, despite the lack of information you provided)
sargent240

ASKER
Thanks for your response.  Your right, I missed the part about the remote computer.  Sorry 'bout that.  I posted a second set of code because you suggested the first code I posted extended a Thread and that was not the way to do it.  I made changes in the code and included it in the next posting or so, so you could see what I did.  I guess the bottom line is I have the code I posted the second time.  I need to start it and be able to pause it from another computer on a lan.  As you can see I don't have a lot of experience in Java and would like to figure this out.  Any assistance you can provide will be appreciated.
ASKER CERTIFIED SOLUTION
CEHJ

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
sargent240

ASKER
That's it.  Your last post was the answer.  The only other thing I had to do to make it work was move the statement:

            private volatile javax.swing.Timer t;

out of the CountDownTimer class so the other methods could see the "t".  I removed the "volatile" and changed the private to public.  I hope that was OK.  It works.  If you see any reason why it should not be done this way I would appreciate knowing.

Thanks for the help and mission accomplished.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CEHJ

If you see any reason why it should not be done this way I would appreciate knowing.
Yes. The only correct part of what you did was to remove the volatile ;)
... so the other methods could see the "t".
 What do you mean there exactly? Which other methods?
sargent240

ASKER
Well, before I got your post with the examples, I moved

            private volatile javax.swing.Timer t;

out of the CountDownTimer class and I could execute t.stop() and t.start() anywhere in the program.  Then I got your post with the examples, put your examples into the CountDownTimer class, put the private volatile javax.swing.Timer t; statement (without volatile) back into the CountDownTimer and both approaches worked.  My terminology is far from accurate I am sure but what I meant was as long as the assignment statement (private volatile javax.swing.Timer t;)  was in the CountDownTimer class without your suggested code the t.stop() and t.start() did not work throughout the program.  When I moved the assignment statement out of the CountDownTimer class to close to the top of the program I could execute t.start() and t.stop() anywhere.  Putting the assignment back into the CountDownTimer class, without the volatile, and adding the two (in C what I called) functions into the CountDownTimer class I now use clt.start() and clt.stop().  Both situations work but I was curious as to what problems I would encounter by moving the t assignment to the top of the program and then using t.start() and t.stop().  Boy I hope I explained that right.
CEHJ

Both the methods i posted in the accepted comment can be accessed from anywhere - they're public methods. There's absolutely no need to access 't' from anywhere other than inside the class that owns that variable and moreover, it's not correct to do so. It's also incorrect, generally, for instance variables to be anything other than private.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
sargent240

ASKER
Thank you for the explanation.  This experience will help understand what is going on in the future as well.  Again thanks for the explanation and have a good new year.
CEHJ

:)