Nowadays I am practicing JavaFX. And I have a problem about ListView. I can make a listener for multiple selections of ListView. However, when I cancel the selection, the listener I made doesn't reflect the cancellation. How can I make a listener that reflects it? The following is a listener that I made.
ListView<String> lv = new ListView<>(FXCollections.observableArrayList(stringArray)); // stringArray is an array that I made.
lv.getSelectionModel().selectedItemProperty().addListener(ch -> {
System.out.println("size: " + lv.getSelectionModel().getSelectedIndices().size());
});
答案 0 :(得分:1)
如果在启用多项选择时选择了更改,请在ListChangeListener
列表中添加selectedItems
(注意selectedItems
,而不是selectedItem
):
lv.getSelectionModel().getSelectedItems().addListener(
(ListChangeListener.Change<? extends String> ch) -> {
System.out.println("size: " + lv.getSelectionModel().getSelectedIndices().size());
}
);
请注意,如果您仅对选择为空感兴趣,则可以
Bindings.isEmpty(lv.getSelectionModel().getSelectedItems()).addListener(
(obs, selectionWasEmpty, selectionIsNowEmpty) -> {
if (selectionIsNowEmpty) {
System.out.println("Nothing is selected");
} else {
System.out.println("Something is selected");
}
}
);