Bitte Wenden Bitte Wenden - 9 months ago 52
Java Question

Have three equally sized VBoxes in HBox in javafx

I have three VBoxes in a HBox. I want all of them to always take one third of the HBox and the full height. I've tried

HBox.setHgrow(<every VBox>, Priority.ALWAYS)
<every VBox>.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
and that worked fine, but when I added a component to one of the VBoxes, it resized itself and became larger than the other ones.

Any idea how to solve this properly?


Use a GridPane instead of the HBox. You can use a collection of column constraints, each with the percentWidth set to give each column equal width.


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 {

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

        RowConstraints rc = new RowConstraints();

        Scene scene = new Scene(root, 400, 400);


    public static void main(String[] args) {