gpt4 book ai didi

java - 尝试从 DefaultListModel 对象中删除元素

转载 作者:行者123 更新时间:2023-12-02 11:11:57 25 4
gpt4 key购买 nike

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

  1. 创建 DefaultListModel 对象
  2. 通过调用 addElement 向其添加 8 个元素 (A..H)
  3. 通过调用removeElement删除项目
  4. 创建一个 Jlist,将我的 DefaultListModel 的引用传递给它
  5. 列表框显示全部 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 );

最佳答案

当您遇到问题时,请访问 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

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

相反,如果您执行类似 philosophers.removeElement("B"); 的操作,您可能会更幸运。

但是,如果我们多读一点 JavaDocs,我们会发现

DefaultListModel#remove

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

specified position in this list. Returns the element that was removedfrom the list.

Throws an ArrayIndexOutOfBoundsException if theindex is out of range (index < 0 || index >= size()).

Parameters:
index - the index of the element to removed

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

关于java - 尝试从 DefaultListModel 对象中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50556912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com