简体   繁体   中英

JavaFX - Make ScrollPane scroll automatically

I have a Label inside a ScrollPane. I am updating the label in a loop (In another thread). How can I update the ScrollPane so it scrolls down (not sideways, this will be done manually) if the user doesnt hold it at a position? Is there a setter for it?

To set the ScrollPane to the bottom automatically set the vvalue of the ScrollPane element, like this:

@FXML private ScrollPane scroll; //this must match the fx:id of the ScrollPane element
scroll.setVvalue(1.0);           //1.0 means 100% at the bottom

If you are using either HBox or VBox within the ScrollPane, try the following:

hBox.heightProperty().addListener(new ChangeListener() {
    @Override
    public void changed(ObservableValue observable, Object oldvalue, Object newValue) {
        scrollPane.setHvalue((Double)newValue );  
    }
});

This works in my code:

scrollPane.vvalueProperty().bind(mainGrid.heightProperty());

in my case scrollPane contains mainGrid

To scroll the scroll pane to the bottom completely, set its vvalue property to 1.0 :

scrollPane.setVvalue(1D);

Note this may not work when called after resizing the scroll pane's content.
In such a case, if delaying the call via Platform.runLater() doesn't fix the problem, consider setting the property's value in response to the content height property invalidation event:

vBox.heightProperty().addListener(observable -> scrollPane.setVvalue(1D));

@Math thanks , that worked!

@FXML private ScrollPane scroll; //this must match the fx:id of the ScrollPane element or be the scrollpane object
scroll.setVvalue(1.0);           //1.0 means 100% at the bottom

And I solved the problem "must be looking at the tab" with this part of code

tab.setOnSelectionChanged(new EventHandler<Event>() {
    @Override
    public void handle(Event arg0) {
        ScrollPane.setVvalue(1.0);
    }        
});

This should do the trick:

// adding a new row
vbox_event.addEventRow((Integer) null, null);
// scroll to bottom
Platform.runLater(new Runnable() {
    @Override
    public void run() {
        scrollpane.setVvalue(1.0);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM