首页 > 解决方案 > 每当其他选择框发生变化时,我如何更新我的选择框?

问题描述

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

标签: javaawt

解决方案


在添加新对象之前,您需要删除列表中的对象:

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


推荐阅读