I don’t think you should use a Calendar
for this. A Calendar
is meant for representing a point in calendar time, not a duration in hours, minutes and seconds. Also, Calendar
is old stuff now and replaced by new and more programmer friendly classes in Java 8 (see the java.time
package).
I understand from the comments that you want a count-down timer. I suggest:
Timer t = new Timer(1000, new ActionListener() {
Duration time = Duration.ofHours(hr).plusMinutes(min).plusSeconds(sec);
@Override
public void actionPerformed(ActionEvent ae) {
time = time.minusSeconds(1);
jLabel2.setText(formatDuration(time));
}
});
t.start();
I am using the Duration
class, one of the classes introduced in Java 8. It is designed for a duration in hours, minutes and seconds, so this is what we need for the job. It doesn’t lend itself well to formatting, though. You may use its toString
method, it will give you a string like PT9M52S
for 9 minutes 52 seconds, probably not what most users find most intuituve. Instead I am using this auxiliary method for formatting:
static String formatDuration(Duration dur) {
long hr = dur.toHours();
Duration remainder = dur.minusHours(hr);
long min = remainder.toMinutes();
long sec = remainder.minusMinutes(min).getSeconds();
return String.format("%02d:%02d:%02d", hr, min, sec);
}