Auto resize ScrollPane


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

1
2
7/30/2014 12:44:29 PM

Accepted Answer

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);
        }
    }
4
7/30/2014 2:29:54 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon