Reputation: 18072
I'm using a JList which displays correctly. However, I'm having trouble removing elements from the list.
JList nameList = new JList(db.getAllNames());
nameList.setVisibleRowCount(6);
nameList.setFixedCellWidth(400);
JButton removeNameButton = new JButton("Remove Name");
removeNameButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String id = nameList.getSelectedValue().toString(); //valid value when button pressed
int index = nameList.getSelectedIndex(); //valid value when value pressed
namesList.remove(index); //ERROR
}
The JList contains 4 names, which displays perfectly and seem to have the correct indexes. (If I check the value System.out.println(copiersList.getModel().getSize());
it always displays 4
Here is the error message:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3
Oddly, if I remove Adam, I do not get an error (but visibly the list does not change and calling .getSize()
method displays 4):
id selected: Adam
index selected: 0
However, any other:
id selected: BobException in thread "AWT-EventQueue-0"
index selected: 1
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 1
at java.awt.Container.remove(Unknown Source)
Upvotes: 2
Views: 1513
Reputation: 285401
Don't remove from the JList itself since the remove(...)
method does not do what you think that it does. It in fact is trying to remove a component that is held in the JList as if it were a JPanel that held other components, even if no such component exists. Instead remove from the JList's model, usually a DefaultListModel. The DefaultListModel class has a removeElement(Object element)
and a removeElementAt(int index)
method that can help you.
i.e.,.
public void actionPerformed(ActionEvent e) {
String id = nameList.getSelectedValue().toString(); //valid value when button pressed
int index = nameList.getSelectedIndex(); //valid value when value pressed
DefaultListModel listModel = (DefaultListModel) namesList.getModel();
listModel.removeElementAt(index);
}
Upvotes: 4