Center Align Rows of a GridPane in JavaFX


I have a GridPane in fxml that has a Text Title and 4 Buttons. The GridPane itself is center aligned, but all the buttons are left aligned inside the column of the grid. I know how to change the alignment of the items using Java code but this is not the ideal situation, as I would like all styling to be handled using FXML and CSS. Can anyone suggest the best way to center align elements of a cell in a GridPane view of JavaFX?

9/15/2014 4:50:28 PM

To set a child of GridPane aligned to center, you need to set the Halignment and Valignment of the child node.

In Java code you can do something similar to :

GridPane.setHalignment(node, HPos.CENTER); // To align horizontally in the cell
GridPane.setValignment(node, VPos.CENTER); // To align vertically in the cell

In FMXL you can achieve a similar effect by :

      ... // other properties
        <Button mnemonicParsing="false" text="Button" GridPane.halignment="CENTER" GridPane.valignment="CENTER" />

There is an easier way to achieve this if you want to align all the nodes of a particular column or row to be aligned in the same order. Instead of adding a halignment / valignment to the node, you can create a ColumnConstraints or a RowConstraints and add them to the GridPane.

        <ColumnConstraints hgrow="SOMETIMES" halignment="CENTER" minWidth="10.0" prefWidth="100.0" />
         ... // More constraints for other columns
         <Button mnemonicParsing="false" text="Button" />

You can similarly add RowConstraints as well.

12/20/2017 9:26:54 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow