java - 每当其他选择框发生变化时,我如何更新我的选择框?
问题描述
所以我有这个问题......我有两个选择框,第一个包含吉他品牌,第二个包含该品牌的吉他类型。我正在使用项目侦听器并且它有效,唯一的问题是它不断添加。例如:我选择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();
}
}
}
推荐阅读
- javascript - Nightwatch/Cucumber - 场景大纲和示例表不起作用
- pytorch - NameError:名称“utils”未在 Pytorch 中定义
- python - TensorFlow-GPU 不会运行 GPU
- asp.net - 数字海洋 Linux 服务器上的 Asp.net 核心 SqlException
- google-sheets - 匹配(同一工作簿)中的(另一个工作表)单元格时的条件格式?谷歌表格
- python - 在 Python 3.7+ 中更改 dict 中的键顺序
- json - 如何从 Bigquery 中的嵌套 JSON 类型列中查询特定内容
- python - 如何在 Unet 架构 PyTorch 中处理奇数分辨率
- python - 在python中四舍五入
- javascript - 在获取 fetch 响应之前条件失败