Hi I am trying to set focus on an item in a listview. After a user opens a file the item is added to the listview, but the issue I am having is that the listview is not setting focus on the new item that was added. I have to click the item in the listview to set focus to it. Is there a way to have the listview to highlight the newly added item right away in JavaFX 2.1 .
Asked
Active
Viewed 4.6k times
1 Answers
59
Assuming that the newly added item has an index of N
,
Selecting it:
listView.getSelectionModel().select(N);
Focusing on it:
listView.getFocusModel().focus(N);
Scrolling to it:
listView.scrollTo(N);
You can use combinations of these and preferably in Platform.runLater()
.
Scroll then select:
Platform.runLater(new Runnable() {
@Override
public void run() {
listView.scrollTo(N);
listView.getSelectionModel().select(N);
}
});

Uluk Biy
- 48,655
- 13
- 146
- 153
-
1I had the same issue using java 8 and the solution was to run the selection after some time has elapsed once the listView was updated: `FxTimer.runLater(Duration.ofMillis(250), () -> listView.getSelectionModel().select(selectedItem));` – Harry244 Jan 08 '18 at 21:06