BJ Dela Cruz
BJ Dela Cruz

Reputation: 5354

Checking if an item already exists in a JComboBox?

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!

Upvotes: 21

Views: 37528

Answers (3)

joseluisbz
joseluisbz

Reputation: 1658

Check with this:

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

or

if(((DefaultComboBoxModel)box.getModel()).getIndexOf(toAdd) < 0) {
  box.addItem(toAdd );
}

Upvotes: 6

Ninja Coding
Ninja Coding

Reputation: 1404

Update:

myComboBox.setSelectedIndex(-1);
String strItem="exists";   
myComboBox.setSelectedItem(strItem);   
if(myComboBox.getSelectedIndex()>-1){ 
    //exists  
}

Upvotes: 0

dogbane
dogbane

Reputation: 274888

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.)

Upvotes: 36

Related Questions