Java JList AbstractListModel添加删除方法不起作用

时间:2017-09-29 12:26:09

标签: java

我有这个ListModel我正在尝试编写,并且只是当项目位于中间左右,而不是第一个或更早时,它会从JList中删除项目时出错最终项目。阵列看起来很好,但第二双眼睛会非常感激。

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.aackerman.swgemu.MyListModel.getElementAt(MyListModel.java:20)
at com.aackerman.swgemu.MyListModel.remove(MyListModel.java:42)
at com.aackerman.swgemu.SWGEmuAdmin$3.actionPerformed(SWGEmuAdmin.java:278)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
public class MyListModel extends AbstractListModel<String> {

    private static final long serialVersionUID = 1L;
    ArrayList<String> list = new ArrayList<>();

    public int getSize() {
        return list.size();
    }

    public String getElementAt(int index) {
        return list.get(index);
    }

    public int getIndexOfItem(String searchTerm) {
        int z = 0;
        for (int i=0;i < list.size();i++) {
            if (list.get(i).equals(searchTerm)){
                z = i;
            }
        }
        return z;
    }

    public void add(String item) {
        list.add(item);
        fireIntervalAdded(this, list.size() - 1, list.size() - 1);
    }

    public boolean remove(String name) {
        boolean success = false;
        int size = list.size();
        for (int i=0;i < size;i++) {
            if (this.getElementAt(i).equals(name)) {
                this.remove(i);
                success = true;
            }
        }
        return success;
    }

    public void remove(int index) {
        list.remove(index);
        fireIntervalRemoved(this, index, index);
    }

    public boolean isEmpty() {
        boolean empty = false;
        if (this.getSize() == 0) {
            empty = true;
        }
        return empty;
    }
}

2 个答案:

答案 0 :(得分:3)

在这段代码中:

    for (int i=0;i < size;i++) {
        if (this.getElementAt(i).equals(name)) {
            this.remove(i);
            success = true;
        }
    }

删除元素后,可以减小列表的大小。但size中的i < size仍然是指列表的原始大小。 只需添加size--即可。

        if (this.getElementAt(i).equals(name)) {
            this.remove(i);
            size--;
            success = true;
        }

答案 1 :(得分:0)

你必须使用迭代器

public boolean remove(String name) {
    boolean success = false;
    Iterator<MyListModel> it = list.iterator();
    while (it.hasNext()) {
        if (it.next().equals(name)) {
            it.remove();
            // If you know it's unique, you could `break;` here
            // or return true
        }
    }
    return success;
}