BJ Peter DeLaCruz BJ Peter DeLaCruz - 6 months ago 174
Java Question

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



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

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