Using Selection and Focus API

To get the currently selected item, you need to use the SelectionModel API:

list.getSelectionModel().getSelectedItem();  // itemlist.getSelectionModel().getSelectedIndex(); // index

It looks a bit wordy, but having all relevant APIs in a helper class is convenient, especially when you want your list to be multi-selectable. To enable multi-select, you need to set SelectionMode.MULTIPLE. For example, for the preceding code block it will look as follows:

// chaptep10/list/MultiselectDemo.javalist.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);// getting selected items for multi-selectObservableList<String> selected = list.getSelectionModel().getSelectedItems();// tracking selectionlist.getSelectionModel().selectedIndexProperty().addListener((obs) ...

Get Mastering JavaFX 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.