strizhechenko
strizhechenko

Reputation: 438

Remove an element from JList

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

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 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?

Upvotes: 1

Views: 2765

Answers (3)

dlunaeri
dlunaeri

Reputation: 11

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.

Upvotes: 1

Waleed Almadanat
Waleed Almadanat

Reputation: 1037

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.

Upvotes: 3

camickr
camickr

Reputation: 324108

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.

Upvotes: 1

Related Questions