Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 829
jlhasson Avatar asked Sep 15 '14 16:09

jlhasson


2 Answers

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.

like image 134
ItachiUchiha Avatar answered Oct 01 '22 16:10

ItachiUchiha


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>
like image 25
James_D Avatar answered Oct 01 '22 18:10

James_D