You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaFX的FXML中让BorderPane底部的Button居中?

让BorderPane底部的Button居中的FXML实现方案

要让BorderPane底部的按钮居中,直接把Button放在bottom区域是行不通的——因为BorderPane对bottom、top这类区域的子节点默认是靠左(bottom/top方向)对齐的,没法直接实现居中效果。你需要把Button嵌套到一个支持居中布局的容器里,下面是两种简单可行的方案:

方案1:使用StackPane(最简洁)

StackPane默认会将所有子节点在自身范围内水平和垂直居中,完全适配这个需求:

<bottom>
    <StackPane>
        <!-- 可选:添加margin来控制容器和BorderPane边缘的间距 -->
        <BorderPane.margin>
            <Insets bottom="8" top="8" left="0" right="0"/>
        </BorderPane.margin>
        <Button text="Center this button" />
    </StackPane>
</bottom>

方案2:使用HBox并设置对齐

如果你更习惯用HBox,只需给它设置alignment="CENTER"属性,就能让内部的Button居中:

<bottom>
    <HBox alignment="CENTER">
        <BorderPane.margin>
            <Insets bottom="8" top="8"/>
        </BorderPane.margin>
        <Button text="Center this button" />
    </HBox>
</bottom>

完整FXML示例

把修改后的bottom区域整合到你的完整布局里,大概是这样:

<BorderPane id="BorderPane" xmlns:fx="http://javafx.com/fxml/1">
    <top>
        <HBox>
            <BorderPane.margin>
                <Insets left="15" right="15" top="15"/>
            </BorderPane.margin>
            <!-- 这里保留你原来top区域的内容 -->
        </HBox>
    </top>
    <bottom>
        <StackPane>
            <BorderPane.margin>
                <Insets bottom="8" top="8"/>
            </BorderPane.margin>
            <Button text="Center this button" />
        </StackPane>
    </bottom>
</BorderPane>

额外提示:如果想调整按钮本身的大小或内边距,可以给Button添加style属性,比如<Button text="Center this button" style="-fx-padding: 6 16; -fx-font-size: 14px;" />来优化视觉效果。

内容的提问来源于stack exchange,提问作者Moritz Schmidt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:28:07