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!
The combo box fires an action event when the user selects an item from the combo box's menu.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With