hudi
hudi

Reputation: 16525

count down timer

I didnt find some easy java swing tutorial of count down timer in java so I decided to implement it to my own way:

javax.swing.Timer t = new javax.swing.Timer(1000, new ClockListener());

class ClockListener implements ActionListener {

Integer m = 5;
Integer s = 0;

public void actionPerformed(ActionEvent e) {  
if ( (s == 0 ) and ( m == 0 ) ) 
    t.stop() 


    if (s == 0) {
        m--;
        s = 60;
    }
    s--;
    _timeField.setText(m.toString() + ":" + ( (s.toString().length() == 1) ? "0" + s.toString() : s.toString() ) );
}
}

_timeField is JTextField

is this correct way how to count down from 5:00 to 0:00 ?

Upvotes: 0

Views: 1089

Answers (1)

jefflunt
jefflunt

Reputation: 33954

If you've implemented it, and it works as expected, that's pretty much the definition of "is it right?" so only you can answer that. There are no massive code style issues here, or anything else, and for the most part you seem to be using Timer as designed.

The question is, "What are you timing?"

Precise chemical/sub-atomic interactions, or safety mechanisms for atomic reactors/air traffic control?

The comments under your original question provide a few pointers on alternative implementations or modifications you can make, depending on what you want to do, and how accurate the timer needs to be. If you need sub-second precision, you would really want to start looking into System.nonoTime().

Your laundry?

If, on the other hand, you're just building a simple countdown timer (e.g. for cooking, reminding you the laundry is done, etc.) then it really only has to be accurate within 1-5 seconds since what you'll be timing is on the order of minutes/hours, and going over or under a little makes no practical difference. I doubt anyone is really going to notice (or even care) if it's a couple seconds off in these sorts of applications. If this is the case, go with the cleaner/easier to understand implementation.

Upvotes: 3

Related Questions