using java version 9 I have some test code to remove a item from a list created by passing a refrence to by DefaultListModel. This is what I do.
The list box displays all 8 items, nothing got removed. code
philosophers = new DefaultListModel<String>();
philosophers.addElement( "A" );
philosophers.addElement( "B" );
philosophers.addElement( "C" );
philosophers.addElement( "D" );
philosophers.addElement( "E" );
philosophers.addElement( "F" );
philosophers.addElement( "G" );
philosophers.addElement( "H" );
philosophers.removeElement(1);
lista = new JList<String>( philosophers );
When ever you have an issue, hit the JavaDocs...
DefaultListModel#removeElement
public boolean removeElement(Object obj)Removes thefirst (lowest-indexed) occurrence of the argument from this list.
Parameters:
obj - the component to be removed
The interesting point here is, the parameter is an Object
, not a index. This means, with Java's auto-boxing, you're actually trying to remove a Integer(1)
, which does't exist in the model.
Instead, if you did something like philosophers.removeElement("B");
, you might have had more luck.
However, if we read a little more into the JavaDocs we find
public E remove(int index)Removes the element at thespecified position in this list. Returns the element that was removed from the list.
Throws an ArrayIndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).Parameters:
index - the index of the element to removed
Ah, that sounds more like what you're after