检查JComboBox中是否已经存在某个项目? [英] Checking if an item already exists in a JComboBox?

查看:42
本文介绍了检查JComboBox中是否已经存在某个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了迭代JComboBox之外,是否有一种简便的方法来检查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) {
   myComboBox.addItem(item);
 }

谢谢!

推荐答案

使用 DefaultComboBoxModel 并调用

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);
}

(请注意,indexOf确实会在项目列表中循环查找所需的项目.)

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

这篇关于检查JComboBox中是否已经存在某个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆