0

Scenario

I have implemented logic, which is intended to update some internal variables, whenever users check certain JCheckBox UI items or select an option in a JComboBox.

My listeners look as follows:

ItemListener listener = event ->
{
    if( event.getStateChange() == ItemEvent.ITEM_STATE_CHANGED )
    {
        // do some business logic
    }
};

uiElement.addItemListener( listener );

I have observed that due to if( event.getStateChange() == ItemEvent.ITEM_STATE_CHANGED ) the business logic never gets triggered, even though item state is clearly changed.

My workaround for this is as follows:

  • JCheckBox: Remove if( event.getStateChange() == ItemEvent.ITEM_STATE_CHANGED ) - it is sufficient not to do this check, as only one item event is fired
  • JComboBox: Replace if( event.getStateChange() == ItemEvent.ITEM_STATE_CHANGED ) by if( event.getStateChange() == ItemEvent.SELECTED ) - otherwise an additional event is fired and handled

Question

While this gets me where I need to go my question remains: What is ItemEvent.ITEM_STATE_CHANGED for? Why won't if( event.getStateChange() == ItemEvent.ITEM_STATE_CHANGED ) resolve to true, when I check a JCheckBox and select an item in my JComboBox?

The documentation reads:

This event id indicates that an item's state changed.

Isn't this true in this scenario?

I also checked other questions, such as this one - but they refer to the itemStateChanged event in general, not to the use of ItemEvent.ITEM_STATE_CHANGED.

Likely I misunderstood what ItemEvent.ITEM_STATE_CHANGED is for. What is its use?

Koenigsberg
  • 1,726
  • 1
  • 10
  • 22
  • 1
    You are comparing the value returned by getStateChange() with the event ID, which is returned by getID(). Read the top of that documentation page—it describes which constants can be returned by getStateChange(). (ITEM_STATE_CHANGED is not one of them.) – VGR Aug 26 '22 at 12:57
  • This explains why the ID check is never passed for `event.getStateChange()`, but it does not explain what `ItemEvent_ITEM_STATE_CHANGED` is used for. – Koenigsberg Aug 26 '22 at 13:02
  • 2
    “This event id indicates that an item's state changed.” seems like a clear explanation to me. Every AWT event and Swing event has an ID which describes the type of event. – VGR Aug 26 '22 at 13:08
  • I see. So this represents the event ID, not the event state. – Koenigsberg Aug 26 '22 at 13:44
  • ITEM_STATE_CHANGED is used in Swing's internal code to set other state changes. – Gilbert Le Blanc Aug 26 '22 at 13:59

0 Answers0