Javafx how to trigger a stage layout update

Eugen Covaci :

I have a very simple Javafx application, that displays a form backed by a grid. On this form I have a checkbox. When the user checks this checkbox, I want to dynamically add another row to the grid.

From my controller:

checkbox.selectedProperty().addListener((obs, oldVal, newVal) - > {
    if (!newVal) {
        // Add Username Label
        gridPane.add(new Label("Username : "), 0, 5);

        // Add Username Text Field
        gridPane.add(new TextField(), 1, 5);
    }
});

The above code works just fine, the only problem is the window layout is not updated to show the new row (I mean the height is not automatically increased), unless I manually resize the window.

Question How to trigger a layout update? (I tried gridPane.requestLayout() but it has no effect)

UPDATE

An ugly workaround would be to hide then show the stage again.

James_D :

To resize a stage to the size of its content, you can use the inherited sizeToScene() method. The following will resize the stage to respond to your new row:

checkbox.selectedProperty().addListener((obs, oldVal, newVal) - > {

    if (!newVal) {
        // Add Username Label
        gridPane.add(new Label("Username : "), 0, 5);

        // Add Username Text Field
        gridPane.add(new TextField(), 1, 5);
        gridPane.getScene().getWindow().sizeToScene();
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3583&siteId=1