JavaFX 绑定时间线显示问题

JavaFX Bind Timeline Display Issue

我目前正在创建一个小游戏,我已经为一轮开始创建了以下方法:

private void startRound(){
    int playerStarting = rnd.nextInt(2) + 1;
    imageBox.managedProperty().bind(imageBox.visibleProperty());

    imageBox.setVisible(false);

    VBox timeBox = new VBox();
    Label timeLabel = new Label();
    timeLabel.setId("RoundTimer-Label");
    timeBox.setAlignment(Pos.CENTER);

    timeBox.getChildren().add(timeLabel);
    gr.add(timeBox, 1, 0, 1, 4);

    Timeline tl = new Timeline(1);
    tl.getKeyFrames().add(new KeyFrame(Duration.seconds(3)));
    timeLabel.textProperty().bind(tl.currentTimeProperty().asString());

    tl.playFromStart();

    timeLabel = null;
    timeBox = null;

    imageBox.setVisible(true);
}

一切 运行 正确,除了一个问题。

tl.currentTimeProperty().asString();

将数字显示为 1000.7 毫秒和 2001 毫秒,如果不是这种情况,我会非常希望。但是,由于 currentTime属性 是一个 属性,因此没有像 .divide(1000) 这样的内置运算符可供我使用,而且我无法将标签文本绑定到 Duration 本身,即使它确实有 .divide(1000) 方法。我在这里遗漏了什么,还是应该以全新的方式来处理这个问题?谢谢

您可以使用绑定来进行任何您想要的转换。

timeLabel.textProperty().bind(
        Bindings.createStringBinding(() -> String.format("%f", Double.valueOf(tl.currentTimeProperty().get().toMillis())/1000.0), tl.currentTimeProperty())
);

你可以给currentTimeProperty()添加监听器,然后用getCurrentTime()在标签上设置当前时间:

tl.currentTimeProperty().addListener(ov -> {
     timeLabel.setText(String.valueOf((int)tl.getCurrentTime().toSeconds()))
});