Tim Kranen
Tim Kranen

Reputation: 4222

Recycling a JavaFX animation

I'm trying to create a simple animation that moves a circle one pixel to the left in JavaFX 2.x, the animation works, but I whenever I try to initiate a second time, it doesn't anymore. I've tried several things, here is the code:

public void handle(KeyEvent t) {
    if (t.getCode() == KeyCode.LEFT) {
        final KeyValue kv = new KeyValue(testPuck.translateXProperty(), -1); 
        final KeyFrame kf = new KeyFrame(Duration.millis(50), kv);
        timeLineToLeft.getKeyFrames().add(kf);
        timeLineToLeft.play();
    }
}

I've tried checking if the timeline didn't equal null and after that removing the keyframe/keyvalue and adding them again. But that didn't help either. Any help on this subject? Documentation seems scarce about this subject. Thanks in advance.

Upvotes: 1

Views: 1517

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34508

Your animation has only one KeyFrame -- final one, there testPuck is located at -1 point. Thus after second call you add new KeyFrame which moves puck from point -1 to point -1 and nothing happens.

Try next:

Note I recreate Timeline each time, where is no reason to keep it:

public void handle(KeyEvent t) {
    if (t.getCode() == KeyCode.LEFT) {
       Timeline timeLineToLeft = new Timeline();
       final KeyValue kv = new KeyValue(testPuck.translateXProperty(), 
            testPuck.getTranslateX() -1);  // note we calculate new value every time
       final KeyFrame kf = new KeyFrame(Duration.millis(50), kv);
       timeLineToLeft.getKeyFrames().add(kf);
       timeLineToLeft.play();
}

If you really want to reuse Timeline object, clear it first:

    timeLineToLeft.getKeyFrames().clear();
    //...
    timeLineToLeft.playFromStart();

Upvotes: 1

Related Questions