javaswingjlistdefaultlistmodellistmodel

Trying to remove a Element from a DefaultListModel object


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.

  1. create a DefaultListModel object
  2. add 8 elements to it (A..H) by calling addElement
  3. remove a item by calling removeElement
  4. create a Jlist pass a reference of my DefaultListModel to it
  5. 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 );      
    

Solution

  • When ever you have an issue, hit the JavaDocs...

    DefaultListModel#removeElement

    public boolean removeElement(Object obj)
    Removes the

    first (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

    DefaultListModel#remove

    public E remove(int index)
    Removes the element at the

    specified 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