JavaFX:如何根据舞台将中心节点置于边框的中央?

标签 java javafx borderpane

我在根据舞台将边框居中的按钮居中时遇到问题。它根据 borderpane 居中,但我希望它位于窗口的确切中心。

enter image description here

我指的是我图片的底部,它有播放按钮和难度选择框。

我正在使用边框让难度部分位于右侧,播放按钮位于中间。

如您所见,play 不在图片的中心。

我想这样做,但我不确定怎么做。我认为我可以将左节点的宽度设置为等于右节点的宽度,但我的左节点没有任何宽度。

// bottom section for positioning
    BorderPane settings = new BorderPane();
    settings.setPadding(new Insets(10));

    // play button
    Button playBtn = new Button("Play");
    settings.setCenter(playBtn);

    // difficulty options
    Label diffLabel = new Label("Difficulty: ");
    ChoiceBox<String> diffBox = new ChoiceBox<String>(FXCollections.observableArrayList(
            "Easy", "Standard", "Hard"
    ));
    diffBox.getSelectionModel().select(1);

    // for wrapping the diffuclty.
    HBox difficulty = new HBox(diffLabel, diffBox);
    difficulty.setAlignment(Pos.CENTER);
    difficulty.setSpacing(10);

    settings.setRight(difficulty);

最佳答案

其中一种可能性是在 BorderPane 的左侧添加一个 Region 以充当分隔符。

来自doc of BorderPane :

The left and right children will be resized to their preferred widths and extend the length between the top and bottom nodes. And the center node will be resized to fill the available space in the middle.

因此在右侧添加一个与 HBox 宽度相同的间隔应该可以解决问题:

Region padderRegion = new Region();
padderRegion.prefWidthProperty().bind(difficulty.widthProperty());
settings.setLeft(padderRegion);

此处左侧间隔符的宽度绑定(bind)到右侧 HBox 的宽度,因此居中的 Node(播放按钮)将居中屏幕。

另一种可能性是在 HBox 中使用各种填充器:

HBox bottomPanel = new HBox();
bottomPanel.setAlignment(Pos.CENTER);

Region padderRegion1 = new Region();
Region padderRegion2 = new Region();
Region padderRegion3 = new Region();
padderRegion1.prefWidthProperty().bind(diffLabel.widthProperty().add(diffBox.widthProperty()));

bottomPanel.getChildren().addAll(padderRegion1, padderRegion2, playBtn, padderRegion3, diffLabel, diffBox);
HBox.setHgrow(padderRegion2, Priority.ALWAYS);
HBox.setHgrow(padderRegion3, Priority.ALWAYS);

关于JavaFX:如何根据舞台将中心节点置于边框的中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384558/

相关文章:

JavaFX:TabPane 上下文菜单,取决于所选选项卡

java - 为什么我在启动简单代码(JavaFX)时遇到问题?

JavaFx 将子节点添加到自定义节点

JavaFX 在边框 Pane 中居中一个可调整大小的圆弧

java - 关于java中使用阻塞队列方法的生产者和消费者模式

java - 缩放在 Java 中存储为 byte[] 的图像

java - 在 Android 中显示来自休息服务器的 gif/动画 ImageView

java - 在 JavaScript 更改 URL 后检索其内容

绑定(bind) JavaFX 2 TableView 元素

java - 如何获取当前加载的fxml文件的名称?