检查 JComboBox 中是否已存在某个项目?

发布于 2024-12-27 15:19:15 字数 364 浏览 1 评论 0原文

除了迭代 JComboBox 之外,是否有一种简单的方法来检查 JComboBox 中是否已存在某个项目?这就是我想做的:

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

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蛮可爱 2025-01-03 15:19:15

使用 DefaultComboBoxModel 并调用 getIndexOf(item) 检查项目是否已存在。如果该项目不存在,此方法将返回-1。以下是一些示例代码:(

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 会循环遍历项目列表以查找您要查找的项目。)

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

给不了的爱 2025-01-03 15:19:15

检查这个:

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

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

Check with this:

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

or

if(((DefaultComboBoxModel)box.getModel()).getIndexOf(toAdd) < 0) {
  box.addItem(toAdd );
}
等你爱我 2025-01-03 15:19:15

更新:

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

Update:

myComboBox.setSelectedIndex(-1);
String strItem="exists";   
myComboBox.setSelectedItem(strItem);   
if(myComboBox.getSelectedIndex()>-1){ 
    //exists  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文