Matteo Matteo - 1 month ago 10
Android Question

Corrispective of android:weight in JavaFX

I'm developing a small software for training in JavaFX.

In Android, inside a

LinearLayout
, I can expand a view to fill the whole space available by setting the variable
android:weight="someValue"
, unfortunately I'm unable to achieve this is JavaFX.

I've tried to work with the max/min/pref height but it didn't work.

Any help would be really appreciated.

Answer

Using a VBox/HBox you can set the vgrow/hgrow static property of the children (or some of them) to Priority.ALWAYS which makes those Nodes grow when the parent grows (assuming they are resizable).

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();
}

To control the relative weights of the children, you could use a GridPane instead and set the percentWidth/percentHeight properties of the ColumnConstraints/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();
}
Comments