I\'ve got a simple Jlist with data from List
, Now I want to remove selected item from Jlist.
Here is the code:
final DefaultListMo
According to the Javadoc for getSelectedIndex():
Returns the smallest selected cell index; the selection when only a single item is selected in the list. When multiple items are selected, it is simply the smallest selected index. Returns -1 if there is no selection
The reason that you're experiencing the error is because for some reason, no items are selected from your list and as such -1 is returned by this method. When you call removeElementAt()
and pass it -1 as a parameter value, it would throw you the exception.
What you need to do is as follows:
public void actionPerformed(ActionEvent arg0) {
int index = list.getSelectedIndex();
if(index >= 0){ //Remove only if a particular item is selected
model.removeElementAt(index);
}
}