【问题标题】:JavaFX Bind Timeline Display IssueJavaFX 绑定时间线显示问题
【发布时间】:2015-09-29 10:40:01
【问题描述】:

我目前正在创建一个小游戏,并且我创建了以下方法来开始回合:

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 毫秒,如果不是这种情况,我会非常喜欢。但是,由于 currentTimeProperty 是一个属性,因此我无法在其上使用像 .divide(1000) 这样的内置运算符,并且我无法将标签文本绑定到 Duration 本身,即使它确实具有 .divide( 1000) 方法。有什么我在这里遗漏的,还是我应该以一种全新的方式来解决这个问题?谢谢。

【问题讨论】:

    标签: java javafx-2


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        相关资源
        最近更新 更多