Can anyone tell me a short way to delete the selected items from my JList
?
I searched on google and here, but I found very many ways. Which way should I use?
As @Andreas_D said, the data centered, more abstract ListModel is the solution. This can be a DefaultListModel. You should explicitly set the model in the JList. So (thanks to comment by @kleopatra):
DefaultListModel model = (DefaultListModel) jlist.getModel();
int selectedIndex = jlist.getSelectedIndex();
if (selectedIndex != -1) {
model.remove(selectedIndex);
}
There are several remove...
methods in DefaultListModel.
By the way, this is a good question, as there is no immediate solution in the API (ListModel).
The JList
component is backed by a list model. So the only recommended way to remove an item from the list view is to delete it from the model (and refresh the view).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With