gpt4 book ai didi

java - 每次其他选择框发生变化时,如何更新我的选择框?

转载 作者:行者123 更新时间:2023-12-02 06:04:32 25 4
gpt4 key购买 nike

所以我有这个问题...我有两个选择框,第一个包含吉他品牌,第二个包含该品牌的吉他类型。我正在使用项目监听器并且它可以工作,唯一的问题是它不断添加。例如:我选择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();
}
}
}

最佳答案

您需要先删除列表中的对象,然后再添加新对象:

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

关于java - 每次其他选择框发生变化时,如何更新我的选择框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com