Solved

Countdown timer

Posted on 2012-12-29
24
547 Views
Last Modified: 2012-12-30
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;
      }
    }
           
    }
0
Comment
Question by:sargent240
  • 12
  • 8
  • 4
24 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 38729163
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?
0
 

Author Comment

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

Author Comment

by:sargent240
ID: 38729381
I would like to be able to start and stop the timer even though the time is not zeros.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38729428
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
0
 

Author Comment

by:sargent240
ID: 38729507
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;
    }
}
0
 

Author Comment

by:sargent240
ID: 38729602
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;
    }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38729648
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
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38729683
I already gave you a solution to this. Which was evidently ignored.
0
 

Author Comment

by:sargent240
ID: 38729725
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.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38729778
lol. What are you on . . .?
0
 

Author Comment

by:sargent240
ID: 38729783
I don't understand your post krakatoa.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38729788
Q.E.D. ;) Bye. G'luck.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:sargent240
ID: 38729800
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.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38729806
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.
0
 

Author Comment

by:sargent240
ID: 38729829
Have a nice day
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38729943
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)
0
 

Author Comment

by:sargent240
ID: 38730239
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.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 38730642
I need to start it and be able to pause it from another computer on a lan.  

Well, to do that, you need to do exactly what i suggested - to expose the Timer methods to the caller:

public void start() {
   t.start();
}

public void stop() {
  t.cancel(); // (Or is it t.stop() - i can't remember)
}

Open in new window

0
 

Author Comment

by:sargent240
ID: 38731234
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38731247
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?
0
 

Author Comment

by:sargent240
ID: 38731364
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38731371
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.
0
 

Author Comment

by:sargent240
ID: 38731379
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38731390
:)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now