-1

我正在尝试使用下面给出的功能在我的 Java FX GUI 中显示同步时钟。

这还包括一个计时器功能,如果Timer=true

private Calendar cal;
private int minute;
private int hour;
private int second;
private String am_pm;

private boolean Timer;
private Integer tseconds;
private void startClock() {
    Timeline clock = new Timeline(new KeyFrame(Duration.millis(Calendar.getInstance().get(Calendar.MILLISECOND)), new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            cal = Calendar.getInstance();
            second = cal.get(Calendar.SECOND);
            minute = cal.get(Calendar.MINUTE);
            hour = cal.get(Calendar.HOUR);
            am_pm = (cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM";
            time.setText(String.format("%02d : %02d : %02d %s", hour, minute, second, am_pm));
            if (Timer) {
                if (tseconds == 0) {
                    Timer = false;
                    //timer.setText("Time Out");
                } else {
                    //timer.setText(tseconds.toString());
                    tseconds--;
                }
            }
        }
    }), new KeyFrame(Duration.millis(Calendar.getInstance().get(Calendar.MILLISECOND))));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}

我对此进行了几次测试,发现时钟多次以可变速度更新。

解决了

寻找下面的解决方案。

4

2 回答 2

0

使用 anAnimationTimer来监听更新:

class MyClass extends AnimationTimer {
   private final static long INTERVAL = 1000L;
   private long nextUpdate;
   public void handle(long now) { 
      if (now >= nextUpdate) {
        ....
        nextUpdate = now + INTERVAL;
   }
}

...
MyClass foo = new MyClass(); 
foo.start();
于 2018-04-14T12:15:10.193 回答
0

解决了这个问题。

我将持续时间设置为当前毫秒,而不是下一秒剩余的毫秒。

只有第一个 KeyFrame 应该具有持续时间(1000-当前毫秒),因为 KeyFrame 将运行的持续时间等于当前秒剩余的毫秒数。

以下关键帧将以 1 秒的间隔运行。

private void startClock() {
    Timeline clock = new Timeline(new KeyFrame(Duration.millis(1000 - Calendar.getInstance().get(Calendar.MILLISECOND)), new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            cal = Calendar.getInstance();
            second = cal.get(Calendar.SECOND);
            minute = cal.get(Calendar.MINUTE);
            hour = cal.get(Calendar.HOUR);
            am_pm = (cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM";
            time.setText(String.format("%02d : %02d : %02d %s", hour, minute, second, am_pm));
            if (Timer) {
                if (tseconds == 0) {
                    Timer = false;
                    //timer.setText("Time Out");
                } else {
                    //timer.setText(tseconds.toString());
                    tseconds--;
                }
            }
        }
    }), new KeyFrame(Duration.seconds(1)));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}
于 2018-04-14T12:19:36.127 回答