Search code examples
javajavafx-8scrollbarscrollpanegridpane

How to create a scrollpane that would scroll in a vertical direction forever?


I'm not sure if this is possible and I couldn't find anything on it, but could I make a scrollpane scroll forever? I am constantly adding new buttons and labels into the window once a button is pressed, and eventually is gets to the bottom. I may be setting it up wrong but here is code:

BorderPane bp = new BorderPane();
GridPane gp = new GridPane();
Button b = new Button("click");
gp.add(b, 1, 1);
ScrollPane sp = new ScrollPane(gp);
bp.setTop(sp);
b.setOnAction(e -> createLabel());

Solution

  • Your'e nearly there, all you now need to do is add the scroll pane as a child of whatever the container is

            GridPane gp = new GridPane();
            Button b = new Button("click");
            gp.add(b, 1, 1);
            b.setOnAction(e -> createLabel());
    
            ScrollPane sp = new ScrollPane(gp);
    
            container.add(sp); // where container is whatever node that'll contain the gridpane.
    

    Play with this code

    public class Controller {
        @FXML private VBox topLevelContainer; // root fxml element
    
        @FXML
        void initialize(){
    
            GridPane gridPane = new GridPane();
            ScrollPane sp = new ScrollPane(gridPane);
            topLevelContainer.getChildren().add(sp);
    
            // add a 100 buttons to 0th column
            for (int i = 0; i < 100; i++) {
                gridPane.add(new Button("button"),0,i);
            }
    
    
        }
    
    }