每次其他选择框更改时如何更新我的选择框?

How can I update my Choice box everytime other choice box changes?

所以我有这个问题...我有 2 个选择框,第一个包含吉他品牌,第二个包含该品牌的吉他类型。我正在使用 Item Listener 并且它可以工作,唯一的问题是它不断添加。比如:我select2次同一个牌子,就会写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();
        } 
    }
}