Both ActionListener and ItemListener are used to fire an event with JCheckBox?
So, what's the difference between them and in which case one of them is preferred to the other?
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.
The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
JCheckBox often uses the methods isSelected and setSelected. To select, or un-select, a box, use the setSelected(boolean) method. To check if a box is selected, use the isSelected() method.
Both ItemListener
as well as ActionListener
, in case of JCheckBox
have the same behaviour. However, major difference is ItemListener
can be triggered by calling the setSelected(true)
on the checkbox. As a coding practice do not register both ItemListener
as well as ActionListener
with the JCheckBox
, in order to avoid inconsistency.
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
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