11

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?

jlhasson
  • 1,516
  • 1
  • 15
  • 23

3 Answers3

20

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
4

In FXML:

<GridPane ...>
  <columnConstraints>

    <!-- one of these for each column: you can obviously have other properties set here if needed -->
    <ColumnConstraints halignment="CENTER" />

  </columnConstraints>
</GridPane>
James_D
  • 201,275
  • 16
  • 291
  • 322
0

You need to align each object in the GridPane individually, not the GridPane itself.

To do this, go yo Layout: ObjectName (ex. Button), and at HAlignment choose CENTER.

Wilhelm Sorban
  • 1,012
  • 1
  • 17
  • 37