JavaFX select item in ListView

2019-03-18 13:26发布

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 .

标签: java javafx-2
1条回答
Ridiculous、
2楼-- · 2019-03-18 14:20

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);
    }
});
查看更多
登录 后发表回答