DreamConspiracy
DreamConspiracy

Reputation: 393

JavaFX Bind Timeline Display Issue

I'm currently creating a little game of sorts, and I have created the following method for the start of a round:

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

Everything is running correctly, except for one issue. The

tl.currentTimeProperty().asString();

Is displaying the number as something like 1000.7 ms and 2001 ms, and I would strongly prefer if that wasn't the case. However since the currentTimeProperty is a Property, there are no built in operators like .divide(1000) that I can use on it, and I can't bind my label text to the Duration itself, even though it does have the .divide(1000) method. Is there something I'm missing here or should I approach this an entire new way? Thanks.

Upvotes: 0

Views: 200

Answers (2)

ItachiUchiha
ItachiUchiha

Reputation: 36722

You can add a listener to the currentTimeProperty() and then use getCurrentTime() to set the current time on the label :

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

Upvotes: 0

WillShackleford
WillShackleford

Reputation: 7008

You can use Bindings to do whatever conversion you want.

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

Upvotes: 1

Related Questions