Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX scroll to bottom of tableview when items are added to it

Tags:

java

javafx

Odd one here, I can't quite work out how to get around this one. I have a tableview that gets populated when a listener to an observable list picks up there has been a change. So this is the code for that:

userController.getAuthImpl().listOfMessages.addListener(new ListChangeListener<Message>() {
    @Override
    public void onChanged(ListChangeListener.Change<? extends Message> c) {
        addMessageToTableView(tblvwBottomAdminNotifications, c.getList());
    }
});


public void addMessageToTableView(TableView<Message> tblvw, ObservableList<? extends Message> observableList){
    tblvw.getItems().clear();
    for(Message msg: observableList)
        tblvw.getItems().add(msg);
}
public ObservableList<Message> listOfMessages = FXCollections.observableArrayList(_listOfMessages);

This works fine and the table automatically updates once an item is added to the listOfMessages. The bit that I would like to do now, is to scroll the listview to the bottom when it is updated. I've attempted adding the following line to the addMessageToTableView method:

tblvw.scrollTo(tblvw.getItems().size()-1);

And have also attempted adding a change listener to the tableview itself like this:

tblvwBottomAdminNotifications.getItems().addListener(new ListChangeListener<Message>(){

    @Override
    public void onChanged(javafx.collections.ListChangeListener.Change<? extends Message> c) {
        tblvwBottomAdminNotifications.scrollTo(c.getList().size()-1);

    }

});

But both error in the same way with the following message:

Exception in thread "RMI TCP Connection(1)-192.168.56.1" java.lang.IllegalStateException: Not on FX application thread; currentThread = RMI TCP Connection(1)-192.168.56.1

Which from my Google skills is JavaFX complaining I'm accessing the tableview from a separate thread. That I can understand, but how should I access it in such a way that when the tableview does get a new item added to it, it scrolls down to it?

Let me know if you need more information.

like image 250
Draken Avatar asked Aug 13 '15 15:08

Draken


1 Answers

How about

Platform.runLater( () -> tblvw.scrollTo(c.getList().size()-1) );
like image 154
Francis Fredrick Valero Avatar answered Sep 29 '22 14:09

Francis Fredrick Valero