当面板 1 未显示时,JavaFX 自动调整面板 2 的大小
JavaFX auto resize panel 2 when panel 1 is not showing
显示面板 1 时。
当面板 1 未显示时。
pane2.prefWidthProperty().bind(
Bindings.when(pane1.visibleProperty())
.then(parent.widthProperty().subtract(pane1.widthProperty()))
.otherwise(parent.widthProperty())
);
pane2.prefHeightProperty().bind(
Bindings.when(pane1.visibleProperty())
.then(parent.heightProperty().subtract(pane1.heightProperty()))
.otherwise(parent.heightProperty())
);
这是假设:
- 您的父窗格和 Pane1 具有定义的大小(非计算大小)。
3 个窗格中的 - None 有任何填充。
- 两个子窗格都没有边距。
只需使用 VBox
并将面板的 vgrow
属性设置为 ALWAYS
:
@Override
public void start(Stage primaryStage) {
CheckBox cb = new CheckBox("Show panel 1");
cb.setSelected(true);
// init panels
Region panel1 = new Region();
Region panel2 = new Region();
panel1.setStyle("-fx-background-color: blue;");
panel2.setStyle("-fx-background-color: red;");
panel1.setPrefSize(300, 200);
panel2.setPrefSize(300, 200);
VBox root = new VBox(cb, panel1, panel2);
// set VBox resizing properties
VBox.setVgrow(panel1, Priority.ALWAYS);
VBox.setVgrow(panel2, Priority.ALWAYS);
VBox.setVgrow(cb, Priority.NEVER);
// add/remove panel1 on CheckBox selection change
cb.selectedProperty().addListener((obs, oldVal, newVal) -> {
if (newVal) {
root.getChildren().add(1, panel1);
} else {
root.getChildren().remove(panel1);
}
});
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
显示面板 1 时。
当面板 1 未显示时。
pane2.prefWidthProperty().bind(
Bindings.when(pane1.visibleProperty())
.then(parent.widthProperty().subtract(pane1.widthProperty()))
.otherwise(parent.widthProperty())
);
pane2.prefHeightProperty().bind(
Bindings.when(pane1.visibleProperty())
.then(parent.heightProperty().subtract(pane1.heightProperty()))
.otherwise(parent.heightProperty())
);
这是假设:
- 您的父窗格和 Pane1 具有定义的大小(非计算大小)。 3 个窗格中的
- None 有任何填充。
- 两个子窗格都没有边距。
只需使用 VBox
并将面板的 vgrow
属性设置为 ALWAYS
:
@Override
public void start(Stage primaryStage) {
CheckBox cb = new CheckBox("Show panel 1");
cb.setSelected(true);
// init panels
Region panel1 = new Region();
Region panel2 = new Region();
panel1.setStyle("-fx-background-color: blue;");
panel2.setStyle("-fx-background-color: red;");
panel1.setPrefSize(300, 200);
panel2.setPrefSize(300, 200);
VBox root = new VBox(cb, panel1, panel2);
// set VBox resizing properties
VBox.setVgrow(panel1, Priority.ALWAYS);
VBox.setVgrow(panel2, Priority.ALWAYS);
VBox.setVgrow(cb, Priority.NEVER);
// add/remove panel1 on CheckBox selection change
cb.selectedProperty().addListener((obs, oldVal, newVal) -> {
if (newVal) {
root.getChildren().add(1, panel1);
} else {
root.getChildren().remove(panel1);
}
});
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}