What is the difference between ChangeListener
and ItemListener
for JCheckBox
and JRadioButton
? Both of them work fine when they are selected/deselected.
I know that some components doesn't support ChangeListener
like the JComboBox
. Other than the reason that ChangeListener
or ItemListener
work for only some components. Is there any difference between them like when are they generated?
Any answer is appreciated. Thanks in advance.
For JButtons, use an Action. For JToggleButtons, JCheckBoxes, and JRadioButtons, use an Action and check its SELECTED_KEY value. If you aren't willing to use Actions, use ActionListener for JButtons, and use ItemListener for JToggleButtons, JCheckBoxes, and JRadioButtons.
A change listener is similar to a property change listener. A change listener is registered on an object — typically a component, but it could be another object, like a model — and the listener is notified when the object has changed.
Interface ItemListenerThe listener interface for receiving item events. The class that is interested in processing an item event implements this interface. The object created with that class is then registered with a component using the component's addItemListener method.
both listeners for JCheckBox
work similarly in that both will fire event upon change in state, whether by clicking or toggle by spacebar or programmatically through doClick()
method (Similar to mouse click). One major difference though is that JCheckBox’s itemListener can be fired through setSelected(boolean
) method which allows one to fire the event based on desired state whereas others will act only after the state is altered. So why is it important ? Consider when application startup, the GUI needed to configure for defined state, and using setSelected
will trigger ItemListener. Note that setSelected
is exclusive to ItemListener and has no effect on ActionListener. Do not register both ActionListener and ItemListener as both will be fired, landing the component in a random state
ChangeListener is notyfied when there's any change to the button state. ChangeListener is not notified of what has changed, only that the object has changed. Item listener is only notyfied when an item is selected; by user or setSelected method. It's also not true that ChangeListener is not notyfied when setSelected method is invoked. It is the change of the object state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With