所以我有这个问题...我有2个选择框,第一个包含吉他品牌,第二个包含该品牌吉他的类型。我正在使用项目监听器,它可以正常工作,唯一的问题是它不断添加。例如:我选择相同品牌的2倍,它将写出2倍的吉他类型,而我只想要吉他的类型。我怎样才能解决这个问题?这是我的侦听器代码:
private class ItemHandler implements ItemListener {
@Override
public void itemStateChanged(ItemEvent event) {
try {
if(event.getSource() == choice_GuitarBrand) {
/*I have a guitar array that will fetch the associated ID of the selected
item given the name */
int id = cmd.fetchGuitarID(choice_GuitarBrand.getSelectedItem());
for(Guitar g : cmd.getSpecificGuitar(id)) {
choice_TypeOfGuitar.add(g.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
添加新对象之前,您需要删除列表中的对象:
private class ItemHandler implements ItemListener {
@Override
public void itemStateChanged(ItemEvent event) {
try {
if(event.getSource() == choice_GuitarBrand) {
/*I have a guitar array that will fetch the associated ID of the selected
item given the name */
int id = cmd.fetchGuitarID(choice_GuitarBrand.getSelectedItem());
choice_TypeOfGuitar.removeAll(); // see https://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html#removeAll()
for(Guitar g : cmd.getSpecificGuitar(id)) {
choice_TypeOfGuitar.add(g.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}