JavaFX 中 android:weight 的校正

Corrispective of android:weight in JavaFX

我正在开发一个用于 JavaFX 培训的小软件。

在 Android 中,在 LinearLayout 中,我可以通过设置变量 android:weight="someValue" 扩展视图以填充整个可用的 space,不幸的是我不能实现这一点的是 JavaFX。

我尝试使用 max/min/pref 高度,但没有成功。

非常感谢任何帮助。

使用 VBox/HBox 您可以设置 children 的 vgrow/hgrow 静态 属性(或某些它们)到 Priority.ALWAYS 这使得那些 Node 在 parent 增长时增长(假设它们可以调整大小)。

private static Region createRegion(String color) {
    Region region = new Region();
    region.setStyle("-fx-background-color: "+color);
    return region;
}

@Override
public void start(Stage primaryStage) {
    VBox vbox = new VBox(
            createRegion("red"),
            createRegion("blue"),
            createRegion("green")
    );
    for (Node n : vbox.getChildren()) {
        VBox.setVgrow(n, Priority.ALWAYS);
    }

    Scene scene = new Scene(vbox);

    primaryStage.setScene(scene);
    primaryStage.show();
}

要控制 children 的相对权重,您可以改用 GridPane 并设置 ColumnConstraintspercentWidth/percentHeight 属性/RowConstraints.

@Override
public void start(Stage primaryStage) throws IOException {
    GridPane root = new GridPane();

    root.getColumnConstraints().addAll(DoubleStream.of(30, 2, 68)
            .mapToObj(width -> {
                ColumnConstraints constraints = new ColumnConstraints();
                constraints.setPercentWidth(width);
                constraints.setFillWidth(true);
                return constraints;
            }).toArray(ColumnConstraints[]::new));

    RowConstraints rowConstraints = new RowConstraints();
    rowConstraints.setVgrow(Priority.ALWAYS);

    root.getRowConstraints().add(rowConstraints);

    root.addRow(0, Stream.of("red", "green", "blue").map(s -> createRegion(s)).toArray(Node[]::new));

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);

    primaryStage.show();
}