Sachini Wickramaratne
Sachini Wickramaratne

Reputation: 599

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?

Upvotes: 2

Views: 4332

Answers (3)

NBTX
NBTX

Reputation: 606

You can use addListener on the list with a ListChangeListener to automatically update the list as items are added to it.

  • This avoids intercepting calls to add items to the list (which can be challenging if using the ObservableList returned by getItems()).
  • You can get the index of the updated item (with change.getTo()).
  • Additionally, I found that it was scrolling to the start of the newly added last element (i.e., to the second-last element) unless I wrapped my call to scrollTo with Platform.runLater.
    public void initialize() {
        // Scroll to the bottom of the list as new items are added.
        messageList.getItems().addListener((ListChangeListener<ChatMessage>) change -> {
            // Loop over the changes in the event.
            while (change.next()) {
                // If the change is that a ChatMessage was added, scroll to the index of that chat message.
                if (change.wasAdded()) {
                    Platform.runLater(() -> messageList.scrollTo(change.getTo()));
                    break;
                }
            }
        });
    }

I added this code to the initialize method of my Controller.

Upvotes: 1

Ilja Tarasovs
Ilja Tarasovs

Reputation: 211

size For example if only 10 items are visible set size = 10;

private void autoScrollMessageList() {
    if (yourList.getItems().size() > size/*where size equals possible items to display*/) {
        yourList.scrollTo(yourList.getItems().size() - 1);
    }
}

Upvotes: 0

fabian
fabian

Reputation: 82461

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

Upvotes: 12

Related Questions