2

Is there another way to remove all items of a JComboBox then removeAllItems()? I use 2 JComboBoxes in mij app and when you select an item from the first combobox the related items should then be shown in the second combobox. When I do this, the items just keep appending after the ones that were already there. When I then first try to clear the combobox by using removeAllItems(), the second combobox is empty and stays empty whenever I change the first combobox... The first combobox keeps all its values... Does anyone see my problem?

festival is the JComboBox:

private JComboBox festival;
private JComboBox zone;

...

public void fillFestivalList(){
    festival.removeAllItems();
    List festivals = OP.fillFestivalList();

    for(Object fest: festivals)
        festival.addItem(fest.toString());
}

public void fillZoneList(String festival){
    zone.removeAllItems();
    List zones = OP.fillZoneList(festival);

    for(Object zoneItem: zones)
        zone.addItem(zoneItem.toString());
}
Maarten Meeusen
  • 482
  • 1
  • 9
  • 23

2 Answers2

4

Regarding,

Is there another way to remove all items of a JComboBox then removeAllItems()?

Simply give the JComboBox a new model.

I would create a new DefaultComboBoxModel<T>, fill it with the newest entries, and then call setModel(...) on my JComboBox, passing in the new model when desired.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • So instead of adding the items to the JComboBox zone, I should add them to DefaultComboBoxModel zoneModel and then do zone.setModel(zoneModel)? – Maarten Meeusen Oct 29 '13 at 22:27
  • +1, @MaartenMeeusen see http://stackoverflow.com/a/5605775/131872 for a simple example – camickr Oct 29 '13 at 22:34
2

You can also Remove all the items in this way , but better to Give JCombobox a new DefaultComboBoxModel like the way @Hovercraft Full Of Eels said

 int itemCount = combo.getItemCount();

        for(int i=0;i<itemCount;i++){
            combo.removeItemAt(0);
         }
Deepak Odedara
  • 481
  • 1
  • 3
  • 12