如何在JavaFX的BorderPane中居中inputPane?附代码片段
嘿,针对你提出的两个JavaFX布局问题,我结合你的代码片段来给出具体的实现方案:
假设你是想把inputPane.getPane()放到mainPane(也就是VBox)里居中,有两种常用方式:
方式一:让整个VBox的内容都居中
直接给VBox设置对齐方式,这样所有添加到VBox里的组件都会居中排列:public MainStage(){ borderPane = new BorderPane(); inputPane=new InputPane(); displayPane=new DisplayPane(); editPane=new EditPane(); mainPane=new VBox(); // 设置VBox的对齐方式为水平+垂直居中 mainPane.setAlignment(Pos.CENTER); // 可选:给组件之间添加间距 mainPane.setSpacing(10); mainPane.getChildren().addAll(inputPane.getPane(), displayPane.getTable(...)); // 后续把mainPane绑定到场景 mainScene = new Scene(mainPane, 800, 600); }方式二:仅让inputPane在VBox里居中,其他组件保持默认对齐
如果你只想让inputPane居中,其他组件(比如displayPane)还是保持原有对齐,可以单独给inputPane设置VBox的对齐约束:public MainStage(){ borderPane = new BorderPane(); inputPane=new InputPane(); displayPane=new DisplayPane(); editPane=new EditPane(); mainPane=new VBox(); // 单独设置inputPane的对齐方式为居中 VBox.setAlignment(inputPane.getPane(), Pos.CENTER); // 可选:禁止inputPane水平拉伸,保持自身宽度 VBox.setHgrow(inputPane.getPane(), Priority.NEVER); mainPane.getChildren().addAll(inputPane.getPane(), displayPane.getTable(...)); }
BorderPane的center区域默认会填充整个可用空间,直接放inputPane会被拉伸填满。要让inputPane保持自身大小并居中,有两种思路:
方式一:用StackPane包裹inputPane后放入BorderPane
StackPane默认会让内部组件居中,用它包裹inputPane再放到BorderPane的中心,就能实现居中效果:public MainStage(){ borderPane = new BorderPane(); inputPane=new InputPane(); displayPane=new DisplayPane(); editPane=new EditPane(); // 创建StackPane作为容器包裹inputPane StackPane centerContainer = new StackPane(); centerContainer.getChildren().add(inputPane.getPane()); // 把StackPane放到BorderPane的center区域 borderPane.setCenter(centerContainer); // 可给BorderPane其他区域添加组件,比如把displayPane放到顶部 borderPane.setTop(displayPane.getTable(...)); mainScene = new Scene(borderPane, 800, 600); }方式二:直接给inputPane设置BorderPane的约束
不想额外嵌套容器的话,可以通过设置BorderPane的对齐和拉伸约束,让inputPane在center区域居中:public MainStage(){ borderPane = new BorderPane(); inputPane=new InputPane(); displayPane=new DisplayPane(); editPane=new EditPane(); borderPane.setCenter(inputPane.getPane()); // 设置inputPane在center区域内居中对齐 BorderPane.setAlignment(inputPane.getPane(), Pos.CENTER); // 禁止inputPane拉伸填满区域,可选添加margin让组件和边框有间距 BorderPane.setMargin(inputPane.getPane(), new Insets(10)); BorderPane.setHgrow(inputPane.getPane(), Priority.NEVER); BorderPane.setVgrow(inputPane.getPane(), Priority.NEVER); // 其他组件设置 borderPane.setTop(displayPane.getTable(...)); mainScene = new Scene(borderPane, 800, 600); }
小提示:如果你的InputPane内部面板没有设置固定大小,可能看不出明显的居中效果,可以临时给它加个背景色(比如inputPane.getPane().setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY, CornerRadii.EMPTY, Insets.EMPTY))))来测试布局哦~
内容的提问来源于stack exchange,提问作者LukeTheWolf

