Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a selected item on ListView in javafx

I have an ListView with items, and developed a delete function which deletes the item. The problem Im facing is when I delete an item, the item below gets deleted as well.

To give you a better understanding. ex:

If I have 5 items in a list and I select and delete "item 2", then item 2 & 3 gets deleted. And items 1, 4 & 5 remains on the list view. If I delete the last item on the list then the item gets deleted and I get a java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Here is my code:

    public void handleDeleteButton() {
    btnDelete.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            final int selectedIdx = playerList.getSelectionModel().getSelectedIndex();
            if (selectedIdx != -1) {
                String itemToRemove = playerList.getSelectionModel().getSelectedItem();

                final int newSelectedIdx =
                        (selectedIdx == playerList.getItems().size() - 1)
                                ? selectedIdx - 1
                                : selectedIdx;

                playerList.getItems().remove(selectedIdx);
                playerList.getSelectionModel().select(newSelectedIdx);
                //removes the player for the array
                System.out.println("selectIdx: " + selectedIdx);
                System.out.println("item: " + itemToRemove);
                players.remove(selectedIdx);

            }
        }
    });
}

I want only the selected item to be deleted. How do I do that? And how do you make the table multi selectable?

players is the list of players used in the ListView.

like image 647
Java Gamer Avatar asked Oct 18 '25 11:10

Java Gamer


1 Answers

You remove 2 items from the list using the following lines:

playerList.getItems().remove(selectedIdx);
        // ^ this should return players
players.remove(selectedIdx);

Remove one of them.

To allow multiple selection, set MultipleSelectionModel.selectionMode to SelectionMode.MULTIPLE.

like image 89
fabian Avatar answered Oct 22 '25 01:10

fabian