I have a JList that lists an arrayList. When I press the button called delete I want to delete the selected element from the list (and ideally the arraylist). At the moment I have the following code, however it is not working. By this I mean that it seems to do nothing if an element is selected and it gives me a ArrayIndexOutOfBoundsException when nothing is selected.
private JList listOrders = new JList(arrayList.toArray());
public void myList() {
listOrders.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
panelForLists.add(listOrders);
}
public void updateList() {
listOrders.setListData(arrayList.toArray());
listOrders.revalidate();
listOrders.repaint();
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == deleteItem) {
int index = listOrders.getSelectedIndex();
listOrders.remove(index);
updateList();
}
}
I assume that maybe it’s because I have to add in a ListSelectionListener somewhere, but I don’t know how I can work this. I’ve searched on the internet for an answer for ages and this was what I came up with from the JList oracle demo.
Thanks a lot!
This is basically what Hovercraft Full Of Eels already answered, but with some more code pointers.
ArrayListcould be used directly asListModelbut this is not possible (as theArrayListdoes not fire any events). You might be tempted to use theJList( Vector )constructor instead, but that one does not allow to modify the vector afterwards. So you are stuck with creating your ownListModel. TheDefaultListModelclass is probably just what you are looking for.actionPerformedmethod always assume there is an element selected. Note that thegetSelectedIndexmethod returns -1 when nothing is selected. The best thing you could do (for the user) is to disable the delete button when nothing is selected, or when more then one element is selected. This can be achieved by letting the action behind the button listen to the selection model of the list, and update its enabled state depending on the selection (do not forget to fire aPropertyChangeEventif needed). If you do not work with anActionbacking up the button, just switch the enabled state of the button directly based on the selection.