Center alignment of grid panel rows in JavaFX

I have a GridPane in fxml that has a text name and 4 buttons. The GridPane itself is centered, but all buttons are left aligned in the grid column. I know how to change the alignment of elements using Java code, but this is not an ideal situation, since I would like the whole style to be processed using FXML and CSS. Can anyone suggest a better way to center cell elements in a GridPane view for JavaFX?

+5
source share
3 answers

To set the GridPane child centered, 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:

 <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 that will be aligned in the same order. Instead of adding halignment / valignment to a node, you can create ColumnConstraints or 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 also add RowConstraints .

+11
source

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> 
+3
source

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

To do this, go to Layout: ObjectName (for example, Button), and in HAlignment, select CENTER.

0
source

Source: https://habr.com/ru/post/1202602/


All Articles