For those who been using Swing to develop Desktop Application will undoubtedly find that it is one of the most flexible and API-rich toolkit available. However such power comes at a price of complexity due to many ways of accomplishing the same task. This post will talk about the common listeners that often confused both beginners and veteran alike.
Some components like JCheckBox and JComboBox have both ActionListener and ItemListener that fire event upon change in the selection state. Many thought that they are synonymous and interchangeable, and indeed the lack of understanding is often the source of confusion not only for those beginners in using Swing but also experienced Swing developer. The inappropiate use of ActionListener and ItemListener are often one of the common source of hard-to-find bugs.
Take for example of JCheckBox. In a way, 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 (Note the listener event model does not guarantee the sequence of event trigger).
if setSelected(true) is called then JCheckBox’s state will be set to Selected, and then the ItemListener will be fired.
If doClick() is called then JCheckBox’s state will be toggled first (eg from => ), and the ActionListener will be fired.
For JCheckBox, read more at http://220.127.116.11/docs/books/tutorial/uiswing/components/button.html#checkbox
Similarly, JComboBox behaves differently for these two types of Listener. JComBoBox offers more options than JCheckBox. Read more at
public class TestActionItemListener
public static void main(String _args)
JFrame _fra = new JFrame(“Testing”);
final JCheckBox _uiChkTestAction = new JCheckBox(“ActionListener”);
public void actionPerformed(ActionEvent _ev)
System.out.println(“State by ActionListener: ” + _uiChkTestAction.isSelected());
final JCheckBox _uiChkTestItem = new JCheckBox(“ItemListener”);
public void itemStateChanged(ItemEvent e)
System.out.println(“State by ItemListener: ” + _uiChkTestAction.isSelected());