在javafx中的HBox中有三个大小相等的VBox



我在一个HBox中有三个VBox。我希望他们所有人都能始终占据HBox的三分之一和整个高度。我尝试过HBox.setHgrow(<every VBox>, Priority.ALWAYS)<every VBox>.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);,效果很好,但当我向其中一个VBox添加组件时,它会调整自己的大小,并变得比其他组件大。

知道如何正确解决这个问题吗?

使用GridPane而不是HBox。您可以使用列约束的集合,每个列都设置了percentWidth,以使每个列具有相等的宽度。

SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class VBoxInGridPane extends Application {
    @Override
    public void start(Stage primaryStage) {
        VBox box1 = new VBox();
        box1.setStyle("-fx-background-color: -fx-background; -fx-background: red ;");
        box1.getChildren().add(new Label("Content"));
        VBox box2 = new VBox();
        box2.setStyle("-fx-background-color: green ;");
        VBox box3 = new VBox();
        box3.setStyle("-fx-background-color: blue ;");
        GridPane root = new GridPane();
        root.add(box1, 0, 0);
        root.add(box2, 1, 0);
        root.add(box3, 2, 0);
        for (int i = 0 ; i < 3 ; i++) {
            ColumnConstraints cc = new ColumnConstraints();
            cc.setPercentWidth(100.0/3.0);
            cc.setHgrow(Priority.ALWAYS);
            root.getColumnConstraints().add(cc);
        }
        RowConstraints rc = new RowConstraints();
        rc.setVgrow(Priority.ALWAYS);
        root.getRowConstraints().add(rc);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

您可以将VBox添加到StackPane,将StackPane添加到HBox。在StackPane中还放置了一个占位符(我通常使用透明的Rectangular),并将其绑定到绑定maxVBoxWidth。这是一个你必须自己定义的Binding

   DoubleBinding maxVBoxBinding = new DoubleBinding() {
        {
            super.bind(vbox1.widthProperty(),vbox2.widthProperty(), vbox3.widthProperty());
        }
        @Override
        protected double computeValue() {
            return Math.max(vbox1.getWidth(), Math.max(vbox2.getWidth(), vbox2.getWidth()));
        }
    }

最新更新