user2370794 user2370794 - 1 month ago 9
Java Question

Setting node layoutProperty() in FXML

I'm creating a UI for a project in javafx. I'm using CSS for the styles, FXML for the structure, and also .java controllers. I'm trying to make my node(s) (i.e. button, borderpane) layout bind to the scene size, so that the window can be resized and the layout stay the same. Normally if the node was defined in a jar file I would use:

button.layoutYProperty().bind((scene.heightProperty().divide(2)));


or something similar, but my nodes are defined within the FXML file.
How can I access the nodes from outside of the FXML file so that I can define the layout or how can I define the layout within the FXML file.
(I am not using and do not intend to use scene builder).

Answer

First, you should never need to do things like this. If you use layout panes you should always be able to choose a combination of layout panes and settings that automatically position the nodes as you want them. The solutions outlined below should never really be needed.

In the controller, you typically don't have direct access to the scene, so you need to listen for when the sceneProperty() is initialized on the node and act accordingly:

public class Controller {

    @FXML
    private Button button ;

    public void initialize() {

        button.sceneProperty().addListener((obs, oldScene, newScene) -> {
            button.layoutYProperty().unbind();
            if (newScene != null) {
                button.layoutYProperty().bind(newScene.heightProperty().divide(2));
            }
        });

        // ...
    }
}

But again, the correct approach here is to choose appropriate layout panes to achieve what you want.