Jason Monsalve Jason Monsalve - 7 months ago 22
Java Question

how to center a label on a pane in javafx

I'd like to set results to the center 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

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