Reputation: 599
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
Reputation: 606
You can use addListener
on the list with a ListChangeListener
to automatically update the list as items are added to it.
ObservableList
returned by getItems()
).change.getTo()
).
change.wasAdded
event, change.getFrom()
returns the list of added nodes too. See the JavaFX ListChangeListener.Change
documentation for more.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
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
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