[英]Countdown Timer jn Java
我必須在網站的所有注冊頁面上顯示倒計時計時器(可能需要3個網頁進行注冊)。 假設時間限制是1小時才能完成注冊,並且用戶花了10分鍾才能完成第一個網頁上的字段,當他單擊“下一步”按鈕轉到第二個網頁時,計時器應顯示49分鍾后的時間。 如何將此功能添加到現有代碼中。
這是我的倒數計時器代碼。
public class CountdownTimer extends JLabel implements ActionListener {
private static final long serialVersionUID = 1L;
private long count;
private long timerStart;
private DateFormat dateFormat;
javax.swing.Timer timer = new javax.swing.Timer(1000, this);
public CountdownTimer(int minutes, int seconds) {
// suppose to show as in 30 MIN 30 SEC.
super(" ", JLabel.CENTER);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, minutes);
cal.set(Calendar.SECOND, seconds);
count = cal.getTime().getTime();
dateFormat = new SimpleDateFormat("mm:ss");
timer.start();
timerStart = System.currentTimeMillis();
long elapsedTime = System.currentTimeMillis()-timerStart;
System.out.println(elapsedTime);
}
public void actionPerformed(ActionEvent e) {
// suppose to countdown till 00 MIN 00 SEC
setText(dateFormat.format(count));
count -= 1000;
if (dateFormat.format(count).equalsIgnoreCase("00:00")) {
closeWindow();
}
}
public void closeWindow() {
System.exit(1);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Countdown Timer");
frame.getContentPane().setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
JPanel panel = new JPanel();
JLabel label = new JLabel("Registration closes in: ");
panel.add(label);
JTextField jTextField = new JTextField();
panel.add(jTextField);
CountdownTimer c = new CountdownTimer(00, 60);
frame.getContentPane().add(c);
frame.setVisible(true);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
這是如此簡單,我什至都不會使用api。
count = 60*minutes + seconds;
然后在動作監聽器中。
count--;
if(count==0) exit(0);
如果您想對此更加健壯。 您應該使用java.time api。
Instant finished = Instant.now().plus(minutes, ChronoUnit.MINUTES).plus(seconds, ChronoUnit.SECONDS);
現在,您可以在動作監聽器中檢查是否已到達結束時間。
if(Instant.now().isBefore(finished)){
//do stuff
} else{
//do your finished stuff.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.