Search code examples
javajavafxrowcentergridpane

Center Horizontally a Row in a GridPane JAVAFX


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


Solution

  • 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);
        }
    }