0

I want to center horizontally one row in my GridPane. I know how to center horizontally a column ( root.getColumnConstraints().get(0).setHalignment(HPos.CENTER);), but I can't find this method for Rows. I can only change the Halignment property of a column and the Valignment property of a row. But what I need is the Halignment of a row, which doesn't exist. So how can I do this ?

This is what I want at the end

Franckyi
  • 243
  • 3
  • 12
  • Possible duplicate of [JavaFx GridPane - how to center elements](http://stackoverflow.com/questions/12816075/javafx-gridpane-how-to-center-elements) – ItamarG3 Nov 07 '16 at 18:23

1 Answers1

0

It's not possible to do this on a using constraints for a whole row, but you can set the property on all Nodes in a row using GridPane.setHalignment, which takes precedence over ColumnConstraints.

Example

@Override
public void start(Stage primaryStage) {
    Text text00 = new Text("text");
    Text text01 = new Text("text");
    Text text02 = new Text("text");
    Text text10 = new Text("text");
    Text text11 = new Text("text");
    Text text12 = new Text("text");
    GridPane gridPane = new GridPane();

    ColumnConstraints cConstraints = new ColumnConstraints();
    cConstraints.setHalignment(HPos.LEFT);
    cConstraints.setHgrow(Priority.ALWAYS);
    gridPane.getColumnConstraints().addAll(cConstraints, cConstraints);
    gridPane.addColumn(0, text00, text01, text02);
    gridPane.addColumn(1, text10, text11, text12);

    GridPane.setHalignment(text11, HPos.CENTER);
    GridPane.setHalignment(text01, HPos.CENTER);

    Scene scene = new Scene(gridPane);

    primaryStage.setScene(scene);
    primaryStage.show();
}

Note that you can also do this after the nodes have been added to the GridPane by iterating through the children:

int alignRow = 1;
for (Node n : gridPane.getChildren()) {
    Integer row = GridPane.getRowIndex(n);
    int rowNumber = row == null ? 0 : rowNumber.intValue();
    if (rowNumber = alignRow) {
        GridPane.setHalignment(n, HPos.CENTER);
    }
}
fabian
  • 80,457
  • 12
  • 86
  • 114