Search code examples
javafxjavafx-8

Purpose of needsLayout property in Parent node


Can someone please let me know what is the purpose of "needsLayout" property in Parent node and how I can benefit from it. I am under the impression that using isNeedsLayout() will tell me whether the node is rendered in the scenegraph or not. But looks like that is not the case. And I am also confused with the description in the Parent API

needsLayout : Indicates that this Node and its subnodes requires a layout pass on the next pulse.

Any help/explanation in regards to this property is highly appreciated. Thank You.


Solution

  • A layout pass determines the position and size of nodes in a scene. Those layout passes are scheduled by JavaFX automatically, if an update to a scene modifies it in a way that requires the size of it an it's ancestors to be recalculated. A layout pass is not immediately executed to avoid recalculating the layout over and over again for consecutive modifications.

    @Override
    public void start(Stage primaryStage) throws IOException {
        Button btn = new Button("click");
        btn.setPrefWidth(60);
        StackPane root = new StackPane(btn);
        btn.setOnAction(evt -> {
            System.out.println("before modification: " + root.isNeedsLayout());
            btn.setPrefWidth(btn.getPrefWidth() + 1);
            System.out.println("after modification: " + root.isNeedsLayout());
        });
    
        Scene scene = new Scene(root, 500, 500);
    
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    In the above example at the time you click the button, the scene is already updated. The layout pass positioned the button and determined it's size. The button event handler updates the prefWidth property of the button which may result in the size/layout changing and therefore a layout pass becomes necessary. When the layout pass happens, the flag gets cleared and only after another modification of the button a new layout pass becomes necessary.

    Usually you don't need to bother with this property. The subclass of Parent you extend from will take care of updating the property.