简体   繁体   English

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

[英]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.使用 java 版本 9 我有一些测试代码从通过将引用传递给 DefaultListModel 创建的列表中删除项目。 This is what I do.这就是我所做的。

  1. create a DefaultListModel object创建一个 DefaultListModel 对象
  2. add 8 elements to it (A..H) by calling addElement通过调用 addElement 向其中添加 8 个元素 (A..H)
  3. remove a item by calling removeElement通过调用 removeElement 删除项目
  4. create a Jlist pass a reference of my DefaultListModel to it创建一个 Jlist 将我的 DefaultListModel 的引用传递给它
  5. The list box displays all 8 items, nothing got removed.列表框显示所有 8 个项目,没有被删除。 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...当您遇到问题时,请点击 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 obj - 要删除的组件

The interesting point here is, the parameter is an Object , not a index.这里有趣的一点是,参数是一个Object ,而不是一个索引。 This means, with Java's auto-boxing, you're actually trying to remove a Integer(1) , which does't exist in the model.这意味着,使用 Java 的自动装箱,您实际上是在尝试删除模型中不存在的Integer(1)

Instead, if you did something like philosophers.removeElement("B");相反,如果你做了像philosophers.removeElement("B");这样的事情philosophers.removeElement("B"); , you might have had more luck. ,你可能有更多的运气。

However, if we read a little more into the JavaDocs we find但是,如果我们多读一点 JavaDocs,我们会发现

DefaultListModel#remove

 public E remove(int index)公共 E 删除(整数索引)
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()).如果索引超出范围(索引 < 0 || 索引 >= size()),则抛出 ArrayIndexOutOfBoundsException。

Parameters:参数:
index - the index of the element to removed index - 要删除的元素的索引

Ah, that sounds more like what you're after啊,这听起来更像是你所追求的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM