Checking if an item already exists in a JComboBox?

和自甴很熟 提交于 2019-12-21 03:34:18

问题


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!


回答1:


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




回答2:


Check with this:

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

or

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



回答3:


Update:

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


来源:https://stackoverflow.com/questions/8899051/checking-if-an-item-already-exists-in-a-jcombobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!