JavaFX - Make ScrollPane scroll automatically

2019-02-17 00:36发布

问题:

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?

回答1:

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


回答2:

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 );  
    }
});


回答3:

This works in my code:

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

in my case scrollPane contains mainGrid



回答4:

@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);
    }        
});


回答5:

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));


回答6:

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);
    }
});