Search code examples
cssjavafxresizeparent

How to auto resize the parent node according to its children


In JavaFX, I would like to have an HBox that automatically resizes both its height and width according to its containing Button children (parent resizes to children).

What is happening right now, by default, is the following: The HBox-width is set to its max-width, making it fit perfectly into its parent StackPane (child resizes to parent). Just like HERE.

The following images describe my question:


WHAT HAPPENS: ex.1

WHAT I NEED: ex.2


Would anyone happen to know how to accomplish the described, using JavaFX and CSS?

These are some snippets of my code:

// JavaFX Code
BorderPane mainPane = new BorderPane();

Button button1 = new Button("Button1");
Button button2 = new Button("Button2");
button1.getStyleClass().add("menuButton");
button2.getStyleClass().add("menuButton");
HBox buttonParent = new HBox();
buttonParent.setId("buttonParent");
// buttonParent.autosize();
buttonParent.setAlignment(Pos.TOP_LEFT);
buttonParent.getChildren().addAll(button1, button2);

mainPane.setCenter(parent);

/* CSS Code */
.menuButton {
    -fx-background-size: cover;
    -fx-background-position: center;
    -fx-border-color: #162338;
    -fx-border-width: 1px;
    -fx-pref-width: 100px;
}

#buttonParent {
    -fx-background-color: #000;
    -fx-border-color: #162338;
    -fx-border-radius: 3px;
    -fx-border-insets: -1px;
    -fx-background-radius: 3px;
    -fx-padding: 5px;
}

Thank you very much!


Solution

  • In JavaFX, the layout of children is managed by the parent layout node. Every layout/pane has its own logic to manage its children, and laso most of these layouts regards child's max min pref values while laying out it.

    In your use case, you can get the layout you wanted in the 2nd image by:

    buttonParent.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE );
    

    This will restrict the size of parent to the combined preferred value of its children buttons. Moreover the parent of buttonParent (i.e. BorderPane) will also take into account the max size of its child.