Vedran
Vedran

Reputation: 43

Swing: JComboBox removing/adding duplicates

My problem has to be able to add and remove items to combobox. those items can be duplicates. I manage to add them:

jComboBox1.addItem(dodatek);

remove first:

 if (jComboBox1.getItemCount() > 0) {
                jComboBox1.removeItemAt(0);

or selected one:

    if (jComboBox1.getSelectedItem() != null) {
        jComboBox1.removeItemAt(jComboBox1.getSelectedIndex());

Problem occurs when having all items removed, and one of them was duplicate. In that case last item remains selected in combobox even though the list is empty! https://i.sstatic.net/rgYP4.jpg

It Also throws exception when trying to remove selected item:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1
    at java.util.Vector.removeElementAt(Vector.java:562)
    at javax.swing.DefaultComboBoxModel.removeElementAt(DefaultComboBoxModel.java:152)
    at javax.swing.JComboBox.removeItemAt(JComboBox.java:759)

This only happens when removing items among which there are duplicates

Upvotes: 0

Views: 1791

Answers (1)

thst
thst

Reputation: 4602

Selected Item and Selected index obviously don't mean the same thing. You need to check, if the selected index is != -1 before calling remove on it.

Selected item is the value selected in the box, selected index is the selected index in the list.

Upvotes: 2

Related Questions