我使用DefaultComboBoxModel和自定义项目填充组合框。每个项目都包含一个ID和一个名称。我遍历一个表,并基于选择,我想从组合框中删除选定的元素。对于我想删除的项目,我从我正在迭代的表中获取ID和名称。我尝试使用removeItem,它接受一个对象。我将ID和Name传入我的自定义Item构造函数,但似乎不起作用。谁能告诉我我在这里失踪了什么?删除Jcombobox中的特定项目
代码用于填充组合框:
Vector<Object> companyList = new Vector<Object>();
while(rs.next()){
companyList.addElement(new Item(rs.getInt(1),rs.getString(2)));
}
DefaultComboBoxModel cmod = new DefaultComboBoxModel(companyList);
companyName.setModel(cmod);
代码自定义项目:
class Item
{
private int id;
private String name;
public Item(int id, String name)
{
this.id = id;
this.name = name;
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public String toString()
{
return name;
}
}
代码移除项目(硬编码在这个例子中):
companyName.removeItem(new Item(50002,"ALLIED WASTE SYSTEMS"));
的removeItem说它需要一个对象,所以我不知道为什么这不起作用。任何帮助,将不胜感激!
应该是'companyList.removeItem(...'而不是'companyName ...'? –
更好地帮助发布[SSCCE]( http://sscce.org/),简短,可运行,可编译,与JCom“JFrame”相关boBox'基于你的类'Item',[可能基于](http://stackoverflow.com/a/14079963/714968),否则搜索'公共无效removeElementAt(INT索引){' – mKorbel