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

时间:2016-05-08 18:28:36

标签: java user-interface javafx javafx-2 javafx-8

我在HBox中有三个VBox。我希望他们所有人总是占据HBox的三分之一和全高。我已经尝试了HBox.setHgrow(<every VBox>, Priority.ALWAYS) <every VBox>.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);并且工作正常,但是当我向其中一个VBox添加一个组件时,它会自行调整大小并变得比其他组件大。

知道如何妥善解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

使用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);
    }
}

答案 1 :(得分:0)

您可以做的是将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()));
        }
    }