Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JCheckbox - ActionListener and ItemListener?

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?

like image 584
TU_HEO DAKAI Avatar asked Mar 27 '12 03:03

TU_HEO DAKAI


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 ActionListener method?

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.

What is the use of JCheckBox?

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 ".

How do I know if JCheckBox is selected?

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.


2 Answers

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.

like image 105
NiranjanBhat Avatar answered Sep 24 '22 21:09

NiranjanBhat


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.

like image 40
JavaTechnical Avatar answered Sep 21 '22 21:09

JavaTechnical