I am facing problem in starting timer and how to place data into date.
This is my code:
Calendar cl = Calendar.getInstance();
cl.set(Calendar.HOUR, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.add(Calendar.HOUR, hr);
cl.add(Calendar.MINUTE, min);
cl.add(Calendar.SECOND, sec);
Date date = cl.getTime();
Timer t =new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
jLabel2.setText(timeFormat.format(date));
}
});
t.start();
Is it correct to use Calendar to place data in date and start timer?
I don’t think you should use a
Calendarfor this. ACalendaris meant for representing a point in calendar time, not a duration in hours, minutes and seconds. Also,Calendaris old stuff now and replaced by new and more programmer friendly classes in Java 8 (see thejava.timepackage).I understand from the comments that you want a count-down timer. I suggest:
I am using the
Durationclass, 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 itstoStringmethod, it will give you a string likePT9M52Sfor 9 minutes 52 seconds, probably not what most users find most intuituve. Instead I am using this auxiliary method for formatting: