Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete selected item from JList

Tags:

java

swing

jlist

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?

like image 837
Bulit Avatar asked Feb 22 '12 20:02

Bulit


2 Answers

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).

like image 140
Joop Eggen Avatar answered Nov 10 '22 23:11

Joop Eggen


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).

like image 23
Andreas Dolk Avatar answered Nov 10 '22 21:11

Andreas Dolk