track changes of nodes bound in JavaFX

2019-07-12 13:56发布

I need to track changes in absolute position and size of a node in javafx.Any change that is caused by resizing window or user manipulation,...

 node.boundsInLocalProperty().addListener(new ChangeListener<Bounds>() {

 @Override
 public void changed(ObservableValue<? extends Bounds> observable,Bounds oldValue, Bounds newValue) {

 System.err.println("Changed!");


 }

 });


 node.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {

 @Override
 public void changed(ObservableValue<? extends Bounds> observable,Bounds oldValue, Bounds newValue) {

 System.err.println("Changed!");


 }

 });

I tried these solutions but doesn't work!

please help me, thanks.

1条回答
贼婆χ
2楼-- · 2019-07-12 14:31

This is quite heavy on performance, so I do not recommend doing this with a large number of nodes in the scene graph, but:

ObjectBinding<Bounds> boundsInScene = Bindings.createObjectBinding(
    () -> node.localToScene(node.getBoundsInLocal()),
    node.localToSceneTransformProperty(),
    node.boundsInLocalProperty());

boundsInScene.addListener((obs, oldBounds, newBounds) -> 
    System.err.println("Changed!"));

You can also do the following, which might be less prone to premature garbage collection:

ChangeListener<Object> listener = (obs, oldValue, newValue) -> 
    System.err.println("New bounds in scene: "+node.localToScene(node.getBoundsInLocal()));
node.localToSceneTransformProperty().addListener(listener);
node.boundsInLocalProperty().addListener(listener);
查看更多
登录 后发表回答