I’m busy on a GUI application in Java in which I sometimes encounter IndexOutOfBoundsExceptions when a value is added to a jList.
The exception seems to occur when a value is selected, and then another is added. I have a listener for selection changes because something needs to happen when the user selects an index, but this event is fired when a new value is added as well. I use a custom ListModel that just extends AbstractListModel and overrides the necessary methods in a perfectly valid way.
- Why does the selection change in the program when a value is added to the list? This is not visually represented.
- Why does the jList allow selection of an index that is not really there?
I have used jList twice now (we’ve recently started doing GUI in school) and I’ve had the problem both times. First time I solved it by clearing selection before a value is added, but that’s not a really good solution. I don’t think this should be necessary.
I don’t know why this occurs, I have no strange code or anything. In pseudo-code, this is what happens:
listmodel.addValue(object);
listmodel.fireIntervalAdded();
//selection event occurs
selectedObject = listmodel.getValueAt(list.getSelectedIndex()); //indexoutofboundsexception
//index = 5, size = 3 (for example) when there are 2 objects in list and first is selected.
I’m not providing more code right now because I think it’s not really relevant. I think anyone that understands perfectly how a jList, its listmodel and its selectionmodel work, will understand what’s wrong. Any help on this is appreciated.
The problem is most likely that you’re calling
fireIntervalAdded(this, 0, list.size())when a single item is added to your list model. The signature is:Note that
index0is the starting index of the added item andindex1is the ending index. Thus for a single itemindex0should be the same asindex1. When you callfireIntervalAddedwith0, list.size(), you are telling the JList that N items have been added, where N=list.size(). Thus theJListthinks there are more items than are in your list model.The same goes for when you remove an item.