Space
Space

Reputation: 1040

JavaFX - Centering button in specific GridPane nodes

I would like to center specifically one button in my GrisPane. It seems to be something missing in its declaration.

Below is my present output with the associated code.

public class Beta extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        root.setGridLinesVisible(true);
        final int numCols = 6 ;
        final int numRows = 12 ;
        for (int i = 0; i < numCols; i++) {
            ColumnConstraints colConst = new ColumnConstraints();
            colConst.setPercentWidth(100.0 / numCols);
            root.getColumnConstraints().add(colConst);
        }
        for (int i = 0; i < numRows; i++) {
            RowConstraints rowConst = new RowConstraints();
            rowConst.setPercentHeight(100.0 / numRows);
            root.getRowConstraints().add(rowConst);         
        }
                
        Button okBtn = new Button("OK");
        okBtn.setAlignment(Pos.CENTER);
        
        root.add(okBtn, 3, 9, 1, 1);    
        
        primaryStage.setScene(new Scene(root, 900, 500));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

Upvotes: 2

Views: 59

Answers (1)

Slaw
Slaw

Reputation: 46170

This code:

Button okBtn = new Button("OK");
okBtn.setAlignment(Pos.CENTER);

Is setting the alignment property of the Button. That property:

Specifies how the text and graphic within the Labeled should be aligned when there is empty space within the Labeled.

Note: A Button is a Labeled (i.e., it's a subtype).

You want to set GridPane's alignment constraints for the Button. You can set constraints for individual child nodes. If I understand your goal correctly, you likely want:

Button okBtn = new Button("OK");
// these are static methods of GridPane
GridPane.setHalignment(okBtn, HPos.CENTER);
GridPane.setValignment(okBtn, VPos.CENTER);

However, if you want every cell in a row/column to have the same alignment, then set the valignment and halignment properties of the appropriate RowConstraints and ColumnConstraints, respectively.

Upvotes: 3

Related Questions