Java JList remove()方法抛出ArrayOutOfBoundsException [英] Java JList remove() method throws an ArrayOutOfBoundsException

查看:82
本文介绍了Java JList remove()方法抛出ArrayOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正确显示的JList.但是,我无法从列表中删除元素.

I'm using a JList which displays correctly. However, I'm having trouble removing elements from the list.

JList nameList = new JList(db.getAllNames());
nameList.setVisibleRowCount(6);
nameList.setFixedCellWidth(400);

JButton removeNameButton = new JButton("Remove Name");

removeNameButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        String id = nameList.getSelectedValue().toString(); //valid value when button pressed
        int index = nameList.getSelectedIndex(); //valid value when value pressed

        namesList.remove(index); //ERROR
    }

JList包含4个名称,它们显示完美,并且似乎具有正确的索引. (如果我检查值System.out.println(copiersList.getModel().getSize());,它将始终显示4

The JList contains 4 names, which displays perfectly and seem to have the correct indexes. (If I check the value System.out.println(copiersList.getModel().getSize()); it always displays 4

这是错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3

奇怪的是,如果我删除了Adam,我不会收到错误消息(但显然列表不会更改,调用.getSize()方法将显示4):

Oddly, if I remove Adam, I do not get an error (but visibly the list does not change and calling .getSize() method displays 4):

id selected: Adam
index selected: 0

但是,其他任何东西:

id selected: BobException in thread "AWT-EventQueue-0" 
index selected: 1
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 1
at java.awt.Container.remove(Unknown Source)

推荐答案

不要从JList本身中删除,因为remove(...)方法不会执行您认为的操作.实际上,它试图删除JList中保存的组件,就好像它是包含其他组件的JPanel一样,即使不存在这样的组件也是如此.而是从JList的 模型 中删除,通常是DefaultListModel. DefaultListModel类具有removeElement(Object element)removeElementAt(int index)方法可以为您提供帮助.

Don't remove from the JList itself since the remove(...) method does not do what you think that it does. It in fact is trying to remove a component that is held in the JList as if it were a JPanel that held other components, even if no such component exists. Instead remove from the JList's model, usually a DefaultListModel. The DefaultListModel class has a removeElement(Object element) and a removeElementAt(int index) method that can help you.

即.

public void actionPerformed(ActionEvent e) {
    String id = nameList.getSelectedValue().toString(); //valid value when button pressed
    int index = nameList.getSelectedIndex(); //valid value when value pressed

    DefaultListModel listModel = (DefaultListModel) namesList.getModel();
    listModel.removeElementAt(index); 
}

这篇关于Java JList remove()方法抛出ArrayOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆