Center Align Rows of a GridPane in JavaFX

lhasson picture lhasson · Sep 15, 2014 · Viewed 21.1k times · Source

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?

Answer

ItachiUchiha picture ItachiUchiha · May 22, 2015

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 :

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

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.

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

You can similarly add RowConstraints as well.