ScrollPane does not immediately resize ViewPort-Height if bound to a Container-Height

395 views Asked by At

Consider a custom component which inherits from VBox. The component's height and width may change depending on some selection. In my Scene I usually have enough vertical space to fit the custom component but it may extend too far horizontally.

I tried placing the custom component inside a ScrollPane and make it grow vertically by binding the ViewPort's minHeight to the custom component's (i.e. the VBox') height. Thus, preventing vertical scrollbars from appearing.

Problem: In JavaFX 8 the ScrollPane only resized to the correct height after another user input (e.g. a click inside the ScrollPane or resizing the window).

The issue is reproducible with the following code:

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        final VBox root = new VBox(5);
        final Scene scene = new Scene(root, 400, 500);

        final ListView<String> listView = new ListView<>();
        final Rectangle rectangle = new Rectangle(600, 300, Color.RED);
        final VBox customComponent = new VBox(rectangle);
        final ScrollPane scrollPane = new ScrollPane(customComponent);
        scrollPane.minViewportHeightProperty().bind(customComponent.heightProperty());
        listView.getItems().addAll("Smaller", "Taller");
        listView.getSelectionModel().selectedItemProperty().addListener((obs, old, item) -> {
            if (Objects.equals(item, "Smaller")) {
                rectangle.setHeight(200);
            } else if (Objects.equals(item, "Taller")) {
                rectangle.setHeight(400);
            }
        });

        root.getChildren().addAll(listView, scrollPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Just click on either Smaller or Taller inside the ListView.

The issue does not appear when adding the rectangle directly to the ScrollPane without the VBox. However, that's not a solution to my problem since I can't easily change the custom component I'm working with. Switching to OpenJFX 11 the ScrollPane correctly grows vertically, but doesn't shrink without another user input. So just upgrading my JavaFX version does not seem to fix the problem.

Is there a way to force the ScrollPane to immediately resize itself or simply another way to fit the ScrollPane to the custom component's height and only scroll horizontally?

0

There are 0 answers