how to center a label on a pane in javafx

Jason Monsalve picture Jason Monsalve · Apr 26, 2016 · Viewed 9k times · Source

I'd like to set results to the centre of Pane.

Label results = new Label("You win");
Pane pane = new Pane();
pane.getChildren().add(results);

I've tried both lines of code below and neither works.

results.setAlignment(Pos.CENTER);
results.setContentDisplay(ContentDisplay.CENTER);

Btw, I know how to get this centered with StackPane and GridPane but in this case I need to use a plain Pane.

Answer

fabian picture fabian · Apr 26, 2016

Pane does not support centering a child. Therefore it has to be done manually, i.e. the layoutX and layoutY positions have to be calculated "manually".

You can achieve this through binding:

results.layoutXProperty().bind(pane.widthProperty().subtract(results.widthProperty()).divide(2));
// procede accordingly with layoutY / height