Checking if an item already exists in a JComboBox?

好久不见. 提交于 2019-12-03 09:55:27

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

Check with this:

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

or

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

Update:

myComboBox.setSelectedIndex(-1);
String strItem="exists";   
myComboBox.setSelectedItem(strItem);   
if(myComboBox.getSelectedIndex()>-1){ 
    //exists  
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!