JCheckbox - ActionListener and ItemListener?

前端 未结 5 1822
南旧
南旧 2020-12-13 08:40

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

5条回答
  •  一个人的身影
    2020-12-13 08:53

    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.

提交回复
热议问题