Search code examples
javalistviewjavafx

javafx listview auto scroll to the end


I'm using JavaFX ListView for the chatroom body of my Chat application. I add to the listview when a message comes or is being sent. This works well but I always have to scroll to find the latest message. Is there any way that I can auto scroll to the bottom so that the latest messages are displayed without having to scroll all the way down?


Solution

  • Use ListView.scrollTo for this purpose:

    public static <T> void addItem(ListView<T> listView, T item) {
        List<T> items = listView.getItems();
        int index = items.size();
        items.add(item);
        listView.scrollTo(index);
    }