开发者

Remove an element from JList

开发者 https://www.devze.com 2023-02-13 05:35 出处:网络
I try to remove selected element from jList, and get exception: Exception in thread \"AWT-EventQueue-0\" java.lang.ArrayInde开发者_开发百科xOutOfBoundsException: 1 >= 0

I try to remove selected element from jList, and get exception:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayInde开发者_开发百科xOutOfBoundsException: 1 >= 0
        at java.util.Vector.elementAt(Vector.java:447)
        at javax.swing.DefaultListModel.remove(DefaultListModel.java:493)
        at gui.Back.jButton2ActionPerformed(Back.java:410)
        at gui.Back.access$300(Back.java:9)
        at gui.Back$5.actionPerformed(Back.java:146)

My code:

DefaultListModel dlm = (DefaultListModel) jList1.getModel();
//System.out.println(dlm.getSize());
dlm.remove(jList1.getSelectedIndex()); //removeElementAt(int i) don't work too
jList1.setModel(dlm);

It's strange, because dlm.getSize(); returns 2.

What I've doing wrong?


The way I would do it is as follows:

final int index = mylist.getSelectedIndex();

if (index >= 0) {
    ((DefaultListModel) mylist.getModel()).removeElementAt(index);
}

You don't need to re-set the ListModel again once data has been removed.


Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example that does this.

Then compare your code with the working code to see what the difference is.

We can't tell you the problem based on a few lines of code.


I've also experienced this issue multiple times. Inspection at variable breakpoints reveal the returned index value < (size - 1), so within parameters that would NOT expect to throw an IOOB Exception. I haven't been able to figure out the cause.

However, I have managed an acceptable workaround, which is to keep my own external model of the the data in an ArrayList and edit that. Then, convert to an array and update through the list.setListData() method. Not very efficient, but functional and the only way I've found to completely preserve the integrity of the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号