Skip to content

Instantly share code, notes, and snippets.

@mikehearn
Created October 3, 2014 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehearn/f639176566d735b676e7 to your computer and use it in GitHub Desktop.
Save mikehearn/f639176566d735b676e7 to your computer and use it in GitHub Desktop.
animatedBind
public static class AnimatedBindInfo {
@Nullable public Timeline timeline;
public NumberBinding bindFrom;
public Runnable onAnimFinish;
}
public static AnimatedBindInfo animatedBind(Node node, WritableDoubleValue bindTo, NumberBinding bindFrom) {
bindTo.set(bindFrom.doubleValue()); // Initialise.
bindFrom.addListener((o, prev, cur) -> {
AnimatedBindInfo info = (AnimatedBindInfo) node.getUserData();
if (info.timeline != null)
info.timeline.stop();
info.timeline = new Timeline(new KeyFrame(UI_ANIMATION_TIME, new KeyValue(bindTo, cur)));
info.timeline.setOnFinished(ev -> {
((AnimatedBindInfo) node.getUserData()).timeline = null;
if (info.onAnimFinish != null)
info.onAnimFinish.run();
});
info.timeline.play();
});
// We must pin bindFrom into the object graph, otherwise something like:
// animatedBind(node, node.opacityProperty(), when(a).then(1).otherwise(2))
// will mysteriously stop working when the result of when() gets garbage collected and the listener with it.
AnimatedBindInfo info = new AnimatedBindInfo();
info.bindFrom = bindFrom;
node.setUserData(info);
return info;
}
@TomasMikula
Copy link

Really nice utility!

Regarding the comment in the code, wouldn't it be sufficient to require the user to store a reference to AnimatedBindInfo to keep the animation working? This would eliminate the need to pass in a Node altogether. The listener would have to be a closure over the AnimatedBindInfo instance instead of over the node.

If you find pinning it to a Node a convenient way to keep the reference, there could be a convenient method AnimatedBindInfo.pin(Node node) to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment