如何在JavaFX BorderPane中央区域居中放置VBox游戏菜单?
How to Center a VBox in the Central Region of a BorderPane (JavaFX)
问题描述
我正在创建一款游戏的首窗口,需制作一个放置在首屏中央的菜单。现有代码片段如下:
BorderPane bp = new BorderPane(); Button Start = new Button("Start"); Button Mute = new Button("Mute"); Button Exit = new Button("Quit"); Button Options = new Button("Options"); /* * Vbox in Center for buttons: * (non-Javadoc) * @see javafx.application.Application#start(javafx.stage.Stage) */ public void start(Stage primaryStage) { VBox vb = new VBox(100); vb.getChildren().addAll...
请问如何将该VBox居中放置在BorderPane的中央区域?
解决方案
实现这个需求其实很简单,两步就能让你的游戏菜单完美居中在首屏中央:
绑定VBox到BorderPane的中央区域
BorderPane专门提供了setCenter()方法来指定中央区域的节点,这是让VBox处于BorderPane中央的核心操作。让VBox内部按钮也居中(可选但推荐)
默认情况下VBox里的控件会从上到下排列并顶在VBox顶部,给VBox设置对齐方式,能让按钮在VBox内部也垂直+水平居中,整体视觉效果更协调。
下面是完整的修正代码:
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class GameMainMenu extends Application { @Override public void start(Stage primaryStage) { BorderPane bp = new BorderPane(); Button startBtn = new Button("Start"); Button muteBtn = new Button("Mute"); Button quitBtn = new Button("Quit"); Button optionsBtn = new Button("Options"); // 创建VBox,设置按钮间距(把100调整为20,可根据游戏界面需求修改) VBox vb = new VBox(20); // 添加所有按钮到VBox vb.getChildren().addAll(startBtn, muteBtn, optionsBtn, quitBtn); // 设置VBox内部内容居中对齐 vb.setAlignment(Pos.CENTER); // 将VBox放到BorderPane的中央区域 bp.setCenter(vb); // 初始化游戏窗口 Scene scene = new Scene(bp, 800, 600); // 窗口大小可按需调整 primaryStage.setScene(scene); primaryStage.setTitle("Game Main Menu"); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
关键细节说明
bp.setCenter(vb):BorderPane的中央区域会自动填充窗口剩余空间,默认会让节点在该区域内居中显示。vb.setAlignment(Pos.CENTER):这一步避免按钮顶在VBox顶部,让菜单整体布局更美观。- 顺便提一句,建议把变量名改成Java规范的小驼峰格式(比如
Start改成startBtn),代码可读性会更高。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

