简体   繁体   English

JAVA使时间由摆动计时器减少到零

[英]JAVA making time to decrease to zero by swing timer

I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer 我有一个毫秒,我将其转换为hh:mm:ss,现在我想使其自动降低超时值。

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ... 例如,当用户看到它时,2:11 0 - > 2:10 59 - > 2:10 58 ......

Below is my code.. 以下是我的代码..

        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();

is it possible? 可能吗?

final Timer t = new Timer(1000, new ActionListener() {
    private long time = 10 * 1000; //10 seconds, for example

    public void actionPerformed(ActionEvent e) {
        if (time >= 0) {
            long s = ((time / 1000) % 60);
            long m = (((time / 1000) / 60) % 60);
            long h = ((((time / 1000) / 60) / 60) % 60);
            timing.setText(h + " hours, " + m + " minutes " + s + " seconds");
            time -= 1000;
        }
    }
});
t.start();

As Peter mentioned in his answer, you shouldn't relay on decreasing a number, since there are not guarantees that actionPerformed is invoked right in every second. 正如Peter在回答中提到的那样,您不应该继续减少数量,因为不能保证每秒都会调用actionPerformed The below is a working example, which stops the timer on finishing (detailed and therefor code): 下面是一个工作示例,该示例在完成时停止计时器(详细的代码)。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {
  private JTextField text;
  private Timer timer;
  private JButton start;

  public Test() {
    super("Countdown timer");
    text = new JTextField("2", 8);
    start = new JButton("Start");
    start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent click) {
        final long current = System.currentTimeMillis();
        try {
          final long limit = Integer.parseInt(text.getText().trim())* 1000; // X seconds
          timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              long time = System.currentTimeMillis();
              long passed = time - current;
              long remaining = limit - passed;
              if(remaining <= 0) {
                text.setText("2");
                timer.stop();
              } else {
                long seconds = remaining/1000;
                long minutes = seconds/60;
                long hours = minutes/60;
                text.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds%60));
              }
            }
            });
          timer.start();
        } catch(NumberFormatException nfe) {
          // debug/report here
          nfe.printStackTrace();
        }
      }});
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(text);
    panel.add(new JLabel(" seconds"));
    panel.add(start);
    add(panel);
  }

  public static void main(String [] args) throws Exception {
    Test frame = new Test();
    frame.setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

The TIMER value is never decremented by the timer event. 计时器事件永远不会减少TIMER值。 Therefore the same time will always be displayed every 1000 milliseconds. 因此,同一时间将始终每1000毫秒显示一次。

Edit: Assuming "timing" is a Swing component the call to repaint should be unnecessary. 编辑:假设“时间”是一个Swing组件,则不需要重新绘制。

A safer option is to take the actual clock time. 一个更安全的选择是获取实际时钟时间。 The reason for this is that your application can stop for pewriods of time. 这样做的原因是您的应用程序可能会停止一段时间。 esp if you machine is busy. esp如果您的机器很忙。 This means a countdown timer might not be called as often as you expect. 这意味着倒数计时器可能不会像您期望的那样经常被调用。 If you use the System.currentTimeMillis() the time will always be right no matter what happens. 如果使用System.currentTimeMillis(),则无论发生什么情况,时间总是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM