我创建了一个扩展AbstractListModel的ComboBoxModel类。我可以将项目添加到组合框中,但是当我尝试删除时,我得到一个异常
线程“AWT-EventQueue-0”中的异常 java.lang.IllegalArgumentException:null source
在第
行this.fireIntervalRemoved(selectedItem,itemIndex,itemIndex);
public class TComboBoxModel extends AbstractListModel implements ComboBoxModel {
private int itemIndex;
private Object selectedItem = null;
private ArrayList<Object> itemList;
public TComboBoxModel() {
itemList = new ArrayList<>();
}
public void addItem(String item) {
this.itemList.add(item);
this.fireIntervalAdded(item, itemIndex, itemIndex);
}
public void removeItem() {
if (itemIndex >= 0 && itemIndex < getSize()) {
this.itemList.remove(itemIndex);
this.fireIntervalRemoved(selectedItem, itemIndex, itemIndex);
}
}
@Override
public void setSelectedItem(Object anObject) {
if ((selectedItem != null && !selectedItem.equals(anObject)) || selectedItem == null && anObject != null) {
this.selectedItem = anObject;
this.fireContentsChanged(anObject, -1, -1);
}
}
@Override
public Object getSelectedItem() {
return selectedItem;
}
@Override
public int getSize() {
return itemList.size();
}
@Override
public Object getElementAt(int index) {
return itemList.get(index).toString();
}
public int getItemIndex() {
return itemIndex;
}
public void increaseItemIndex() {
itemIndex++;
}
public void decreaseItemIndex() {
itemIndex--;
}
}
答案 0 :(得分:1)
您可能应该将其更改为:
if (selectedItem != null) {
fireIntervalRemoved(this, itemIndex, itemIndex);
}
由于您无法删除某个项目,除非您知道要删除哪个项目。
您还必须适当地设置itemIndex
变量。
public void setSelectedItem(Object anObject) {
if ((selectedItem != null && !selectedItem.equals(anObject)) || selectedItem == null && anObject != null) {
this.selectedItem = anObject;
this.fireContentsChanged(anObject, -1, -1);
itemIndex = ... index in itemList where anObject is located (or -1 if not found) ...
}
}
感谢@kiheru指出第一个问题的问题。
答案 1 :(得分:1)