Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an item already exists in a JComboBox?

Tags:

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!

like image 575
BJ Dela Cruz Avatar asked Jan 17 '12 17:01

BJ Dela Cruz


People also ask

Which event gets generated when you select an item from a JComboBox?

The combo box fires an action event when the user selects an item from the combo box's menu.

What is the method used in adding an item into JComboBox class?

The addItem() method is used to add an individual Object to a JComboBox . By default, the first item added to a JComboBox will be the selected item until the user selects another item.


1 Answers

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

like image 111
dogbane Avatar answered Sep 21 '22 14:09

dogbane