【问题标题】:Countdown Timer jn JavaJava中的倒数计时器
【发布时间】:2015-10-08 15:10:53
【问题描述】:

我必须在网站的所有注册页面上显示倒数计时器(可能是 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);
    }
}

【问题讨论】:

  • 也许您应该查找使用哪些技术来创建 WEB 页面,然后我们可以提供帮助。目前您使用的是 Swing(不是 WEB)
  • 您是否在开始时检查了计数等于多少?我敢打赌 elapsedTime 始终为零,但偶尔为 1。也许您应该查看Duration
  • 你应该为 Java web 使用动态 web 项目,而不是 swing。如果你确实使用了 swing,也许也可以看看 mvc 模式?

标签: java swing timer


【解决方案1】:

这太简单了,我什至不会同时使用 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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2015-11-13
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多