Why won't javafx rectangles display their color when sizing to the parent container's getWidth/Height?

Viewed 28

I'm trying to use rectangles as the background for text labels by putting them behind the VBox text in a StackPane, but when I try using the VBox's getWidth() or getHeight() values for the rectangle's size, the rectangle does not appear. I suppose I could

This works, displaying the blue rectangle behind the text, though not the size I want:

StackPane tadPane = new StackPane();
tadPane.setBorder(border);
Rectangle tadRec = new Rectangle();
VBox tadBox = new VBox();
Label totalXP = new Label("Total XP: ");
Label diff = new Label("Difficulty: ");
tadBox.getChildren().addAll(totalXP,diff);
tadRec.setWidth(50);
tadRec.setHeight(50);
tadRec.setFill(Color.BLUE);
tadPane.getChildren().addAll(tadRec,tadBox);

But this doesn't, the rectangle is not visible:

StackPane tadPane = new StackPane();
tadPane.setBorder(border);
Rectangle tadRec = new Rectangle();
VBox tadBox = new VBox();
Label totalXP = new Label("Total XP: ");
Label diff = new Label("Difficulty: ");
tadBox.getChildren().addAll(totalXP,diff);
tadRec.setWidth(tadBox.getWidth());
tadRec.setHeight(tadBox.getHeight());
tadRec.setFill(Color.BLUE);
tadPane.getChildren().addAll(tadRec,tadBox);

I can't understand why this would be happening. Raw numbers in the setWidth/Height work, but the getWidth/Height from the VBox should be returning numbers too if the labels with text are inside.

1 Answers

The reason for this is that at the time you retrieve the height and width, no layout pass has happened for the VBox so the size is still the initial one of 0 x 0.

You could use bindings to make the size update on a layout:

tadRec.widthProperty().bind(tadBox.widthProperty());
tadRec.heightProperty().bind(tadBox.heightProperty());

though it could be much simpler to simply apply a a background to the VBox instead of using a Rectangle:

tadBox.setStyle("-fx-background-color: blue;");
Related