JavaFX How to make a GridPane fit to ScrollPane parent?

I need page with a grid where entering some data so, using SceneBuilder , I put a GridPane inside an AnchorPane. The gridpane I need has huge height so I wrap it inside a ScrollPane and make the ScrollPane fitting to AnchorPane. But now when I expand the window gridpane doesn’t resize like it doesn’t fit the ScrollPane. How Can I make gridpane resizing when I resize the window?

Answer

Set the fitToWidth property of the ScrollPane to true and make sure both the anchors of the ScrollPane are set.
You may also need to use appropriate constraints on the GridPane columns to resize the children of the GridPane.

Example

<AnchorPane xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ScrollPane fitToWidth="true"
                    AnchorPane.leftAnchor="10"
                    AnchorPane.rightAnchor="10"
                    AnchorPane.topAnchor="10"
                    AnchorPane.bottomAnchor="10">
            <content>
                <GridPane hgap="10">
                    <padding>
                        <Insets topRightBottomLeft="10"/>
                    </padding>
                    <columnConstraints>
                        <ColumnConstraints /> 
                        <ColumnConstraints fillWidth="true" hgrow="ALWAYS" /> 
                    </columnConstraints>
                    <children>
                        <Text text="Family Name:"/>
                        <TextField GridPane.columnIndex="1"/>
                    </children>
                </GridPane>
            </content>
        </ScrollPane>
    </children>
</AnchorPane>

Leave a Reply

Your email address will not be published. Required fields are marked *