Difference between ChangeListener and ItemListener
Asked Answered
P

2

10

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.

Pignut answered 1/7, 2013 at 11:15 Comment(0)
V
6

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

Vick answered 1/7, 2013 at 11:20 Comment(3)
the question is about change- vs. itemListener, not about action vs. itemListener :-) Seeing it accepted, your crystal ball revealed what the OP was really after, +1!Nevillenevin
Item event (itemStateChanged method call) is raised only once when you release a button. Change event (stateChanged method call) is raised twice: when you press a button and again when you release a buttonVick
if you want to clarify your answer, editing it is the way to go :-) anyway, your comment is not precise enough: you can't really predict how often a ChangeListener is notified for a single selection change triggered by a user gesture (because its an unspecific event, broadcasting about multiple aspescts of the model's state)Nevillenevin
C
1

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.

Christadelphian answered 1/7, 2013 at 11:55 Comment(2)
I meant that the mouse cursor entered the button.Christadelphian
ahhh, I see, thanks: the technical name of that property is rolloverNevillenevin

© 2022 - 2024 — McMap. All rights reserved.