Przemek Krysztofiak
Przemek Krysztofiak

Reputation: 924

How to recognize Node bounds change in Scene?

Lets say I have some TextField which is placed deep in the panes layout structure. I want add listener or recognize in some way that TextField changed its position (x, y) in Scene. The question is - how can I achive it in a proper, reusable way?

I provide some test code. To recreate please drag stage border, which will cause TextField position change.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        TextField textField = new TextField();
        Button button = new Button("Button");

        HBox hBox = new HBox(textField, button);
        hBox.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);

        StackPane stackPane = new StackPane(hBox);
        stackPane.setPrefSize(600., 400.);
        Scene scene = new Scene(stackPane);
        stage.setScene(scene);
        stage.show();
    }
}

Upvotes: 2

Views: 285

Answers (1)

fabian
fabian

Reputation: 82461

Add a listener to the localToSceneTransform property of the node.

node.localToSceneTransformProperty().addListener((o, oldValue, newValue) -> {
    System.out.println("transform may have changed");
});

Note that this

  1. Yields some "false positives", i.e. it may notify you, if the position hasn't actually changed.
  2. Registering too many of those listeners to nodes may decrease the performance of your application, since doing so involves listening to changes for all nodes in the hierarchy up to the root node.

In addition to this a listener to the boundsInLocal property may be needed, if you also want to be notified to the size of the node itself changing.

Upvotes: 5

Related Questions