Monday, January 23, 2023

JComboBox breaks on Exception in ActionListener

This article was posted originally on JRoller on the 7/9/2011. 

We had a bug reported to us the other day, when one combobox suddenly stopped working. You could select any item, the other components would not react to the selection. Looking through the logs, we noticed a nice NullPointerException, but only one. It seems like the first exception in our ActionListener was breaking something in our combobox. So I looked at the source code of JComboBox, and here is what I found: 
    protected void fireActionEvent() {
    if (!firingActionEvent) {
    firingActionEvent = true;
    // Loop through Listeners
    //call to listener.actionPerformed(e)
    firingActionEvent = false;
    }    
    }


Notice the firingActionEvent boolean, that is here to prevent an infinite loop of event. If an exception occurs in the listener, the boolean firingActionEvent remains at true, and no action will ever be processed. I filed a bug report to Oracle, so that they add a try/finally block to ensure the boolean goes back to false at the end of the method.

Looking a bit further in the code, I could find the same pattern applied in the setSelectedItem() method:

     // Must toggle the state of this flag since this method    
    // call may result in ListDataEvents being fired.
    selectingItem = true;
    dataModel.setSelectedItem(objectToSelect);
    selectingItem = false;

 I guess it would be a good idea to apply the same fix here.

No comments:

Post a Comment