在JavaFX中同步时间线时钟的最佳方法是什么?

时间:2018-04-14 11:40:53

标签: java javafx real-time-clock

我正在尝试使用下面给出的功能在我的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();
}

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

解决

寻找下面的解决方案。

2 个答案:

答案 0 :(得分:0)

使用AnimationTimer收听更新:

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();

答案 1 :(得分:0)

解决了这个问题。

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

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

以下KeyFrames将以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();
}