Solved

Java Countdown timer problem

Posted on 2011-02-20
7
626 Views
Last Modified: 2012-06-21
I am attaching some code I am using for a countdown timer.  It will not let me start a time of less than one hour.  I have tried sending it 0 hours, 2 minutes, and 27 seconds but it starts with 12 hours, 2 minutes, and 27 seconds.  Also I don't know how to stop it before it runs the time to 00:00:00.  Any Ideas.
Cheers!


public class CountDownTimer implements ActionListener {
    private long count;
    private int hours;
    private int minutes;
    private int seconds;
    private DateFormat df;

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in  HR:MIN:SEC.

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

      javax.swing.Timer t = new javax.swing.Timer(1000, this);
      t.start();
    }

    public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC
        jtAudioCutsTimer.setFont(new Font("sansserif", Font.PLAIN, 36));
      jtAudioCutsTimer.setText(df.format(count));
      count -= 1000;
    }
}
0
Comment
Question by:sargent240
  • 4
  • 3
7 Comments
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
It is probably not the intended use of Calendar or DateFormat but to get it to do what you want, you just have to change the format that you are passing to SimpleDateFormat. At the moment, it is printing in 12 hour format AM/PM but you should set it to 24 hour format. Just change

 df = new SimpleDateFormat("hh:mm:ss");

to

 df = new SimpleDateFormat("HH:mm:ss");


And to stop it you just have to call stop() on the Timer object that you created. You can do this in at least 2 ways; you can create a variable in the class to store the Timer object (at the moment, it is only in scope in the constructor so you cant use it outside that function) and then you can do whatever you want with it anywhere in the class, or you can get to the object through the ActionEvent object in the actionPerformed function with

 ((javax.swing.Timer) e.getSource()).stop();

It just depends in which function that you need to call stop()
0
 

Author Comment

by:sargent240
Comment Utility
Thank you very much for your reply!  I changed the hh from lower to upper case, set the hour to 0, the minutes to 2, and the seconds to 16 and the counter started with 12:02:16.  Did I miss something?
Thanks - Cheers
0
 

Author Comment

by:sargent240
Comment Utility
Another thought, maybe I need to take another approach.  Is there a fairly simple way to do what I am doing here.  I don't mind the way it is so if I can get it fixed great or you might have seen or been involved with some code that does what I need.  Again THANKS!
sarge
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
Comment Utility
Ahh, I didn't do enough testing (or was just lucky enough to not see an additional problem). The change I made above would have working if you were testing it out while your current timezone was AM. That's why it worked fine for me this morning when I tried it out. I just tried it again and it went back to 12 instead of 0. The problem is that I am now in PM too.

To fix that problem, you have to make 1 additional change, from ...

 cal.set(Calendar.HOUR, hours);

to

 cal.set(Calendar.HOUR_OF_DAY, hours);

As to your second post, I would probably suggest that you do take another approach. Which approach that is depends on info that only you know, such as exactly how this is going to be used, etc. The problem with the above is that you are using a Calendar/DateFormat object to represent a duration of time, but it is not really meant for that. It is meant to be able to specify a point in time.

As an example of where this may present an issue for you, it may not do what you expect it to do on the daylight savings changeover days. What is happening is that Calendar.getInstance() is getting you a calendar that is set to the current date and time, and then you are just setting the time to be eg. 2 miinutes and 16 seconds past midnight, and then you are making it just print out the time part of that. On the DLS days if someone entered a timer duration of 5 hours, the timer would expire either 4 or 6 hours later, depending on which DLS day it is.

Unfortunately the standard Java libraries have nothing to support durations of time the way you want to use it. So I can see 2 alternatives, if you will only ever have timer durations in hours, minutes & seconds then it may be easier to just do everything manually, ie. count = ((hours * 60 + minutes) * 60 + seconds) * 1000; and then manually convert that back to fields and manually format the string. Or if now (or down the track) you will want to properly support durations of days, months, etc, I would look into a library called Joda Time (http://joda-time.sourceforge.net/index.html) that can handle those type of things properly, including formatting not just date/times but periods and durations, etc.
0
 

Author Comment

by:sargent240
Comment Utility
Great.  I was messing around while waiting to hear from you,I changed Hours to Hours_Of_Day and it started to work.  Thank you for the narration on the calendar class, it is great info and and will go into my three ring binder.  I am writing some code to automate my radio station.  The timer is used to count down the audio cut that is playing.  To date we have not had a cut that has lasted more that 7 or 8 minutes.  It may come to a time when we would play a cut that would last an hour or two but that is it.  It is only used so the man in the control room knows whether he has enough time to go to the men's room or not.  I think this will work fine.  I have only one other problem and that is when it comes to 00:00:00 I would like it to stop, not turn over to 23:00:00 and start down.  If I can solve that problem I would use the code until I needed to change it but if stopping at 00:00:00 is a problem I will recode it.  Any thoughts?
0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
In this case the easiest (but not necessarily the best) way to do it would probably be to just look for the string being equal to "00:00:00", so you would have something like...

      jtAudioCutsTimer.setText(df.format(count));
      if(df.format(count).equals("00:00:00")
            ((javax.swing.Timer) e.getSource).stop();
      count -= 1000;

But I am not sure if you will need to clean up else, notify some other part of the code that the timer has stopped, etc. It is a bit hard to say without seeing a bigger picture of the code.

(Note: the nicer ways to do this would be if you did go for 1 of the 2 alternatives that I mentioned above. It would then look a bit more like... if(count <= 0) .......)
0
 

Author Closing Comment

by:sargent240
Comment Utility
The best yet
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Reading variable length EBCDIC in SAS 9 74
wefewf 2 42
java continue statement 10 70
python sqlite question 11 42
A short article about problems I had with the new location API and permissions in Marshmallow
This is about my first experience with programming Arduino.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

763 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

13 Experts available now in Live!

Get 1:1 Help Now