2015-09-29 32 views
0

我目前正在建立各種各樣的小遊戲,我創建了下面的方法,圓的開始:JavaFX的綁定時間軸顯示問題

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)方法。有沒有我在這裏失蹤的東西,還是應該以一種全新的方式來解決這個問題?謝謝。

回答

1

你可以使用綁定來做任何你想要的轉換。

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

您可以將監聽器添加到currentTimeProperty()然後用getCurrentTime()設置標籤上的當前時間:

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