JavaFX BorderPane内的按钮如何自动适配对应区域尺寸?
问题说明
正在开发JavaFX布局,核心使用BorderPane布局,最终目标是通过按钮实现四向区域分块铺展的布局效果。目前已做出的效果和预期高度接近,但所有尺寸都是通过手动硬编码调整实现的,尝试过调整BorderPane和按钮的相关API,始终没找到让按钮自动适配所属区域尺寸的方案,窗口缩放时容易出现布局错位。
目前已写出的测试代码如下:
@Override public void start(Stage stage) throws Exception { BorderPane parent = new BorderPane(); Scene scene = new Scene(parent, 500, 500); // 顶部按钮 Button button1 = new Button("top"); parent.setTop(button1); button1.setPrefSize(500,20); BorderPane.setAlignment(button1, Pos.CENTER); // 底部按钮 Button button2 = new Button("bottom"); parent.setBottom(button2); button2.setPrefSize(500,20); BorderPane.setAlignment(button2,Pos.CENTER); // 左侧按钮 Button button3 = new Button("left"); parent.setLeft(button3); button3.setPrefSize(50,500); BorderPane.setAlignment(button3, Pos.CENTER); // 右侧按钮 Button button4 = new Button("right"); parent.setRight(button4); button4.setPrefSize(50,500); BorderPane.setAlignment(button4,Pos.CENTER); // 舞台基础配置 stage.setScene(scene); stage.setTitle("Hello JavaFX"); stage.show(); }
问题原因与调整方法
BorderPane本身的布局逻辑天然适配这种四向分块的需求:
- 放置在top、bottom区域的子节点,默认会自动横向撑满整个BorderPane的宽度,仅保留自身设置的偏好高度
- 放置在left、right区域的子节点,默认会自动纵向撑满整个BorderPane的高度,仅保留自身设置的偏好宽度
之前的代码无法实现自动适配,核心是两个操作违背了BorderPane的默认布局规则:
- 手动给按钮设置了全尺寸的
setPrefSize,把按钮尺寸硬编码为固定像素,不会随窗口缩放自动调整 - 给每个按钮设置了
BorderPane.setAlignment(..., Pos.CENTER)的对齐规则,这个规则会让子节点按照自身偏好尺寸居中摆放,不会自动撑满对应区域的空间
具体调整步骤:
- 删除所有硬编码的
setPrefSize调用,不要给按钮写死全尺寸 - 删除所有给按钮设置的居中对齐代码,让BorderPane使用默认的撑满布局规则
- 仅给按钮设置对应方向的偏好尺寸:顶、底按钮只设置需要的偏好高度,左、右按钮只设置需要的偏好宽度
调整后的可自动适配的代码:
@Override public void start(Stage stage) throws Exception { BorderPane parent = new BorderPane(); Scene scene = new Scene(parent, 500, 500); // 顶部按钮:仅设置偏好高度,宽度由BorderPane自动撑满 Button button1 = new Button("top"); button1.setPrefHeight(20); parent.setTop(button1); // 底部按钮:仅设置偏好高度,宽度由BorderPane自动撑满 Button button2 = new Button("bottom"); button2.setPrefHeight(20); parent.setBottom(button2); // 左侧按钮:仅设置偏好宽度,高度由BorderPane自动撑满 Button button3 = new Button("left"); button3.setPrefWidth(50); parent.setLeft(button3); // 右侧按钮:仅设置偏好宽度,高度由BorderPane自动撑满 Button button4 = new Button("right"); button4.setPrefWidth(50); parent.setRight(button4); // 舞台基础配置 stage.setScene(scene); stage.setTitle("Hello JavaFX"); stage.show(); }
调整后无论如何缩放窗口,顶、底按钮都会自动跟随窗口宽度铺满对应区域,左、右按钮都会自动跟随窗口高度铺满对应区域,完全不需要硬编码全像素尺寸。
内容的提问来源于stack exchange,提问作者somerandomname
相关产品推荐
相关产品推荐

