java - 将标签绑定(bind)到场景的底部中心 - JavaFX

标签 java javafx position

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

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();
    }
}

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

enter image description here

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

enter image description here

预先感谢所有帮助我的人!

最佳答案

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

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);
    }
}

关于java - 将标签绑定(bind)到场景的底部中心 - JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085842/

相关文章:

java - 带时间的日志文件名不能正常工作

java - 如何将字节数组转换为文件

java - 创建忽略鼠标和按键事件的 JavaFX 透明窗口

javascript - ui.position 相对位置的错误值

html - 将{位置: absolute;} always position my element with respect to its first parent?

css - 我可以将我的 CSS 背景定位到 "bottom minus x pixels"吗?

java - 有没有办法以编程方式获取我的 Hadoop 集群信息?

java - AES 解密给出不一致的结果

JavaFX ComboBox<POJO> 不更新值

java - 如何使用JRE部署JavaFX 11 Desktop应用程序