20

Is there an easy way to check if an item already exists in a JComboBox besides iterating through the latter? Here's what I want to do:

 Item item = ...;
 boolean exists = false;
 for (int index = 0; index < myComboBox.getItemCount() && !exists; index++) {
   if (item.equals(myComboBox.getItemAt(index)) {
     exists = true;
   }
 }
 if (!exists) {
   myComboBox.addItem(item);
 }

Thanks!

BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84

3 Answers3

35

Use a DefaultComboBoxModel and call getIndexOf(item) to check if an item already exists. This method will return -1 if the item does not exist. Here is some sample code:

DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {"foo", "bar"});
JComboBox box = new JComboBox(model);

String toAdd = "baz";
//does it exist?
if(model.getIndexOf(toAdd) == -1 ) {
    model.addElement(toAdd);
}

(Note that under-the-hood, indexOf does loop over the list of items to find the item you are looking for.)

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 2
    +1, But I'm surprised that the `-1` return value is not noted in the API. – mre Jan 17 '12 at 17:52
  • You could also create a DefaultComboBoxModel subclass that overrides the addElement method and uses the getIndexOf method to check for duplication prior to calling the superclass version of addElement. This way you don't have to invoke the de-duplication code manually, and the ComboBox will do all the work automatically for each item added to it. – Dyndrilliac Mar 01 '14 at 17:39
  • 1
    @mre if you look into source `DefaultComboBoxModel` you see that `int getIndexOf(Object anObject)` return `objects.indexOf(anObject)`. and `objects` is `Vector`. – 1ac0 Nov 21 '14 at 16:12
6

Check with this:

if(((DefaultComboBoxModel)box.getModel()).getIndexOf(toAdd) == -1) {
  box.addItem(toAdd );
}

or

if(((DefaultComboBoxModel)box.getModel()).getIndexOf(toAdd) < 0) {
  box.addItem(toAdd );
}
joseluisbz
  • 1,491
  • 1
  • 36
  • 58
-1

Update:

myComboBox.setSelectedIndex(-1);
String strItem="exists";   
myComboBox.setSelectedItem(strItem);   
if(myComboBox.getSelectedIndex()>-1){ 
    //exists  
}
Ninja Coding
  • 1,357
  • 1
  • 16
  • 26
  • From [the docs for JComboBox](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)), "If `anObject` is not in the list and the combo box is uneditable, it will not change the current selection." i.e. this solution doesn't work as it stands. However, if you set the selected index to -1 and *then* do this, then it'll work. – captainroxors Jun 16 '14 at 16:55
  • @captainroxors i updated the code, i did not test i trust on you haha. – Ninja Coding Sep 08 '15 at 18:17