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?
Asked
Active
Viewed 3,604 times
1
-
Have a look [here](https://stackoverflow.com/questions/20333396/javafx-make-scrollpane-scroll-automatically) and maybe [there](https://stackoverflow.com/questions/13156896/javafx-auto-scroll-down-scrollpane), too... – deHaar Aug 08 '18 at 11:14
-
Hi thanks for the quick response. The thing is I'm not using a scroll pane. Im using only a ListView. Is there any workaround for this? – Sachini Wickramaratne Aug 08 '18 at 11:21
2 Answers
9
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);
}

fabian
- 80,457
- 12
- 86
- 114
-
Would you by any chance know how to access the cell at a given index? – Sachini Wickramaratne Aug 09 '18 at 06:23
-
@SachiniWickramaratne Why do you want to do this? That is usually a bad idea (depending on what exactly "accessing the cell" means). Cells for certain indices may or may not be present at a given time and may come into view later. If this is about highlighting the new object(s) or something like this: This is possible but I cannot properly explain it in comments. I suggest asking a new question about this. – fabian Aug 09 '18 at 11:01
-
this is the purpose https://stackoverflow.com/questions/51765043/javafx-listview-update-dynamically – Sachini Wickramaratne Aug 09 '18 at 11:04
0
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);
}
}

Ilja Tarasovs
- 181
- 2
- 13