Question

I want to resize ScrollPane to fit the parent component. I tested this code:

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {

        BorderPane bp = new BorderPane();
        bp.setPrefSize(600, 600);
        bp.setMaxSize(600, 600);
        bp.setStyle("-fx-background-color: #2f4f4f;");

        VBox vb = new VBox(bp);

        ScrollPane scrollPane = new ScrollPane(vb);
        scrollPane.setFitToHeight(true);
        scrollPane.setFitToWidth(true);

        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);

        Scene scene = new Scene(scrollPane);

        stage.setScene(scene);
        stage.show();
    }

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

But as you can see I don't see tree scroll bars. Is there anything wrong into my code?

enter image description here

Was it helpful?

Solution

The scrollbars won't show up because

  1. You have the policy set to ScrollBarPolicy.AS_NEEDED
  2. The width and height of the scroll bars are automatically resized to that of its' container, which, in this case, is your resizable Vbox.

To fix this, you could remove setFitToHeight and setFitToWidth and leave them as false.

Note that ScrollBarPolicy could also be set to ALWAYS as opposed to AS_NEEDED, which will keep the scroll bars even when the window is expanded.

Refer here for more information using ScrollPane

ScrollPane API: setFitToHeight

    public class MainApp extends Application {

        @Override
        public void start(Stage stage) throws Exception {

            BorderPane bp = new BorderPane();
            bp.setPrefSize(600, 600);
            bp.setMaxSize(600, 600);
            bp.setStyle("-fx-background-color: #2f4f4f;");

            VBox vb = new VBox(bp);

            ScrollPane scrollPane = new ScrollPane(vb);
            //scrollPane.setFitToHeight(true);
            //scrollPane.setFitToWidth(true);

            scrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS);
            scrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS);

            Scene scene = new Scene(scrollPane);

            stage.setScene(scene);
            stage.show();
        }

        public static void main(String[] args) {
            launch(args);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top