Search code examples
javaerror-handlingcomboboxjcombobox

Remove all Items in a JCombo Box and not trigger an event when the combo box is empty


I have a Jcombobox which is loaded with data from a database.

When the user performs a certain action, I reload the items in the combo-box, by REMOVING ALL the items in the combo-box and adding a fresh list of items to it.

Now here is the thing, I have an event listener added to the combo box. And the event is triggered even when the combo-box is null.

I have tried to catch the null by all these:

if (categoryCBox.getModel().getSize() == 0){
         //dont do anything with the combobox   
        }

if(categoryCBox.getSelectedIndex() == -1){
        //dont do anything with the combobox 
}

if(categoryCBox.getItemCount() == 0){
        //dont do anything with the combobox 
}

if (categoryCBox.getSelectedItem().toString().equals("")){

}

However the itemStateChangedEvent is still triggered as a result of removing all items in the combo-box and gives me a null pointer to the method attached to it. How can I avoid the null- pointer error.


Solution

  • How can I avoid the null- pointer error.

    1. Remove the listener from the combo box
    2. reload the items
    3. Add the listener back to the combo box