Search code examples
javajavafxvboxgridpane

Fit VBox to parent GridPane


I have GridPane which has two columns: first contains fixed-size ImageView, the second has VBox with Text elements. I need this VBox to fit the column width. Grid has right dimensions, ImageView too, but VBox in second column fits to text which it contains, not to parent (grid).

VBox box = new VBox();
// all three texts can be changed during program execution by user
// (so 'box' width cannot be based on children widths)
box.getChildren().addAll(new Text("1"), new Text("2"), new Text("3"));
box.setStyle("-fx-background-color: red;");

Image image = ...; // image is always 150x150 px
ImageView imgView = new ImageView(image);
GridPane grid = new GridPane();
grid.add(imgView, 0,0);
grid.add(box,1,0);
grid.add(new Text("another content"), 0,1,2,1);

According to given example i want 'box' to have the same width as second column of 'grid' object. How to fix this?

enter image description here Container with green border: GridPane grid Container with lightblue border: VBox box GridPane has red background, VBox has pink background. You can see that it clearly DOES NOT fit it's parent width.

Thanks in advance


Solution

  • You can set the Hgrow to the children of the GridPane. Setting the HGrow as Always will allow them to occupy the total width available to them.

    As box is a child of gridPane, you can apply the property using the static method setHgrow

    GridPane.setHgrow(box, Priority.Always);
    

    For similar issues with height, you can use setVGrow(Node child, Priority value).