Removing all Items from a combo box in Java

chathura picture chathura · Sep 3, 2012 · Viewed 89.4k times · Source

I need to remove all items from the combo box

    int itemCount = combo.getItemCount();

    for(int i=0;i<itemCount;i++){
        combo.removeItemAt(0);
     }

This code will remove all items except the last one. It gives a NullPointerException. How to fix that?

Answer

Dan D. picture Dan D. · Sep 3, 2012

The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.

However, I sugeest you should better use the removeAllItems(); method:

combo.removeAllItems();