Search code examples
javajavafxalignmentjavafx-8gridpane

JavaFX How to Center Multiple Components side by side


I have 2 components: Label & Button. I want to put them side by side & align them together in CENTER. But I failed to do so, as they are still aligned LEFT but not CENTER.

enter image description here

My code as below:

Label sloganLbl = new Label("With cost as low as $1.99, you can own a fraction share of U.S. stock. No account yet?");
sloganLbl.getStyleClass().add("blue-small-font");


Button signUpBtn = new Button("Open account now");
signUpBtn.getStyleClass().add("green-btn-small-font");

GridPane topGrid = new GridPane();

topGrid.setHgap(20);
topGrid.add(sloganLbl, 0, 0);
topGrid.add(signUpBtn, 1, 0);
topGrid.setGridLinesVisible(true);

GridPane.setHalignment(sloganLbl, HPos.RIGHT);
GridPane.setHalignment(signUpBtn, HPos.LEFT);

BorderPane topBorder = new BorderPane();
topBorder.setPadding(new Insets(15, 10, 15, 10));
topBorder.setCenter(topGrid);

topBorder.getStyleClass().add("blue-small-font");
topGrid.getStyleClass().add("blue-small-font");

borderPane.setTop(topBorder);

The problem is topBorder.setCenter(topGrid); is not able to center the content in center. Seems topGrid is taking up full width, not just total width of it's 2 columns.

How can I achieve the center alignment? Thanks!


Solution

  • You can update the GridPane with a gap filler column on the left and on the right.

    ColumnConstraints leftFiller = new ColumnConstraints();
    leftFiller.setHgrow(Priority.ALWAYS); // Fills the space left on the left side
    ColumnConstraints rightFiller = new ColumnConstraints();
    rightFiller.setHgrow(Priority.ALWAYS); // Fills the space left on the right side
    topGrid.getColumnConstraints().addAll(leftFiller, new ColumnConstraints(), 
        new ColumnConstraints(), rightFiller);
    
    topGrid.add(sloganLbl, 1, 0);
    topGrid.add(signUpBtn, 2, 0);
    

    This snippet will create a GridPane with 4 columns. The first and the last is growing when the GridPane becomes resized, the 2 inner columns hold the Label and the Button.

    Please notice that the Label and the Button are now placed into the second and third column.