so I have this problem... I have 2 choice boxes, the first one contains guitar brands, and the second one the type of guitars that brand has. I am using an Item Listener and it works, the only problem is that it keeps adding. For example: I select 2 times the same brand, it will write 2 times the type of guitar, and I just want the types of guitars. How can I fix this? Here's my code of the listener:
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();
}
}
}
You need to remove the objects in the list before adding new ones:
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.