试图从 DefaultListModel 对象中删除一个元素

Trying to remove a Element from a DefaultListModel object

使用 java 版本 9 我有一些测试代码可以从通过将引用传递给 DefaultListModel 创建的列表中删除一个项目。 这就是我所做的。

  1. 创建一个 DefaultListModel 对象
  2. 通过调用 addElement
  3. 添加 8 个元素 (A..H)
  4. 通过调用 removeElement 删除项目
  5. 创建一个 Jlist,将我的 DefaultListModel 的引用传递给它
  6. 列表框显示所有 8 个项目,没有删除任何内容。 代码

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

遇到问题时,请点击 Java文档...

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

这里有趣的一点是,参数是一个Object,而不是索引。这意味着,使用 Java 的自动装箱,您实际上是在尝试删除模型中不存在的 Integer(1)

相反,如果你做了类似 philosophers.removeElement("B"); 的事情,你可能会更幸运。

但是,如果我们多读一点Java文档,我们会发现

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

啊,这听起来更像你想要的