Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ChangeListener and ItemListener

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.

like image 845
JavaTechnical Avatar asked Jul 01 '13 11:07

JavaTechnical


People also ask

What is the difference between ActionListener and ItemListener?

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.

What is a ChangeListener?

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.

What is Item listener?

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.


2 Answers

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

like image 57
rags Avatar answered Oct 21 '22 13:10

rags


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.

like image 20
luke657 Avatar answered Oct 21 '22 11:10

luke657