[英]how to center a label on a pane in javafx
I'd like to set results to the centre of Pane
. 我想将结果设置在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
. 顺便说一句,我知道如何以StackPane
和GridPane
为中心,但是在这种情况下,我需要使用普通的Pane
。
Pane
does not support centering a child. Pane
不支持将孩子居中。 Therefore it has to be done manually, ie the layoutX
and layoutY
positions have to be calculated "manually". 因此,它必须手动完成,即layoutX
和layoutY
位置必须“手动”计算。
You can achieve this through binding: 您可以通过绑定来实现:
results.layoutXProperty().bind(pane.widthProperty().subtract(results.widthProperty()).divide(2));
// procede accordingly with layoutY / height
I was boring with binding, so i made some simple. 我对绑定很无聊,所以我做了一些简单的事情。 My "MessageBox" is always at center since then. 从那时起,我的“ MessageBox”始终处于中心位置。 Center Pane to AnchorPane. 中心窗格到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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.