将标签绑定到场景的底部中心 - JavaFX

Binding label to bottom-center of scene - JavaFX

我想弄清楚如何在场景底部完美地居中和绑定标签。我这里有一个简单的测试应用程序来展示我正在使用的是什么以及我的问题是什么。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class LabelTest extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Pane root = new Pane();
        Scene scene = new Scene(root, 400, 400);

        Label label = new Label("Testing testing 1 2 3");

        label.layoutXProperty().bind(scene.widthProperty().divide(2).subtract(label.getWidth() / 2));   //Should align label to horizontal center, but it is off  
        label.layoutYProperty().bind(scene.heightProperty().subtract(label.getHeight() + 35));          //Aligns the label to bottom of scene

        root.getChildren().add(label);
        stage.setScene(scene);
        stage.show();
    }
}

我的定位背后的逻辑对我来说很有意义,所以我不确定为什么它不是水平居中的。我在下面附上了一张截图来显示输出的样子:

下面是我希望它看起来像的更多内容(还有一点偏差,但你明白了)

在此先感谢所有帮助我的人!

问题是您在绑定时采用了 width/height 的值。在这种情况下,它将为 0,因为它们尚未呈现。您还需要绑定这些属性以进行计算。

label.layoutXProperty().bind(scene.widthProperty().divide(2).subtract(label.widthProperty().divide(2)));
label.layoutYProperty().bind(scene.heightProperty().subtract(label.heightProperty().add(35)));

让布局管理员为您进行布局:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LabelTest extends Application {

    @Override
    public void start(Stage stage) throws Exception {

        Label label = new Label("Testing testing 1 2 3");
        BorderPane root = new BorderPane();
        //center label by
        //BorderPane.setAlignment(label, Pos.CENTER);
        //root.setBottom(label);
        //OR
        root.setBottom(new StackPane(label));
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}