检查 JComboBox 中是否已存在某个项目?
除了迭代 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
DefaultComboBoxModel
并调用getIndexOf(item)
检查项目是否已存在。如果该项目不存在,此方法将返回-1
。以下是一些示例代码:(请注意,在幕后,
indexOf
会循环遍历项目列表以查找您要查找的项目。)Use a
DefaultComboBoxModel
and callgetIndexOf(item)
to check if an item already exists. This method will return-1
if the item does not exist. Here is some sample code:(Note that under-the-hood,
indexOf
does loop over the list of items to find the item you are looking for.)检查这个:
或
Check with this:
or
更新:
Update: