Jason Monsalve
Jason Monsalve

Reputation: 37

how to center a label on a pane in javafx

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.

Upvotes: 3

Views: 12336

Answers (2)

Gábor Veres
Gábor Veres

Reputation: 1

I was boring with binding, so i made some simple. My "MessageBox" is always at center since then. Center Pane to AnchorPane. May work with other Controls and Containers, i didn't try.

double w = (anchorpane.getWidth()/2)-(panel.getWidth()/2);
double h = (anchorpane.getHeight()/2)-(panel.getHeight()/2);
panel.setLayoutX(w); panel.setLayoutY(h);

Upvotes: -1

fabian
fabian

Reputation: 82491

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

Upvotes: 5

Related Questions