KS o.o
KS o.o

Reputation: 3

How do I enable multiple selection mode is ListView?

I tried to enable multiple selection mode to ListView. However, it still seems to be in single selection mode when I test it and I'm not sure what went wrong. Help? Thank you. Here is my code:

ObservableList<String> alphabets
            = FXCollections.observableArrayList("Aa", "Bb", "Cc",
                    "Dd", "Ee");

ListView<String> AlphabetsLv = new ListView<String>(alphabets);
AlphabetsLv.setPrefSize(80, 80);
AlphabetsLv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

Upvotes: 0

Views: 1215

Answers (1)

Olzen
Olzen

Reputation: 76

Press/hold down Shift or Ctrl while selecting.

Shift -> selects range, top selection to bottom selection.
Ctrl -> adds individual selected rows.

If you want multiple selection without using keys, you can use the cell factory from this post: Deselect an item on an javafx ListView on click

In your case:

    AlphabetsLv.setCellFactory(alv -> {
        ListCell<String> cell = new ListCell<>();
        cell.textProperty().bind(cell.itemProperty());
        cell.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
            AlphabetsLv.requestFocus();
            if (!cell.isEmpty()) {
                int index = cell.getIndex();
                if (AlphabetsLv.getSelectionModel().getSelectedIndices().contains(index)) {
                    AlphabetsLv.getSelectionModel().clearSelection(index);
                } else {
                    AlphabetsLv.getSelectionModel().select(index);
                }
                event.consume();
            }
        });
        return cell;
    });

Upvotes: 1

Related Questions