JCheckbox - ActionListener and ItemListener?

JavaSwingActionlistenerJcheckboxItemlistener

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

For reference, here's an sscce that illustrates the difference. Console:

SELECTED
ACTION_PERFORMED
DESELECTED
ACTION_PERFORMED

Code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/q/9882845/230513 */
public class Listeners {

    private void display() {
        JFrame f = new JFrame("Listeners");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JCheckBox b = new JCheckBox("JCheckBox");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getID() == ActionEvent.ACTION_PERFORMED
                    ? "ACTION_PERFORMED" : e.getID());
            }
        });
        b.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println(e.getStateChange() == ItemEvent.SELECTED
                    ? "SELECTED" : "DESELECTED");
            }
        });
        JPanel p = new JPanel();
        p.add(b);
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Listeners().display();
            }
        });
    }
}

Solution 4 - Java

I use addActionListener for JButtons while addItemListener is more convenient for a JToggleButton. Together with if(event.getStateChange()==ItemEvent.SELECTED), in the latter case, I add Events for whenever the JToggleButton is checked/unchecked.

Solution 5 - Java

I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.

The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.

The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.

>Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;

    public RadioButtonsAndCheckBoxesTest(){
	    funny = "You are not ugly, you were just born... different";
		serious = "Recommend powdered soap in prison!";
		political = "Trump can eat a little Bernie, but will choke on his     Birdie";
		
		display = new JLabel(funny);
		Font defaultFont = new Font("Ariel",Font.PLAIN,20);
		display.setFont(defaultFont);
		
		bold = new JCheckBox("Bold",false);
		bold.setOpaque(false);
		italic = new JCheckBox("Italic",false);
		italic.setOpaque(false);
		
		//Color itemBackground =
		
		funnyQuote = new JRadioButton("Funny",true);
		funnyQuote.setOpaque(false);
		seriousQuote = new JRadioButton("Serious");
		seriousQuote.setOpaque(false);
		politicalQuote = new JRadioButton("Political");
		politicalQuote.setOpaque(false);
		
		quotes = new ButtonGroup();
		quotes.add(funnyQuote);
		quotes.add(seriousQuote);
		quotes.add(politicalQuote);
		
		JPanel primary = new JPanel();
		primary.setPreferredSize(new Dimension(550, 100));
		
		Dimension standard = new Dimension(500, 30);
		
		JPanel radioButtonsPanel = new JPanel();
		radioButtonsPanel.setPreferredSize(standard);
		radioButtonsPanel.setBackground(Color.green);
		radioButtonsPanel.add(funnyQuote);
		radioButtonsPanel.add(seriousQuote);
		radioButtonsPanel.add(politicalQuote);
		
		JPanel checkBoxPanel = new JPanel();
		checkBoxPanel.setPreferredSize(standard);
		checkBoxPanel.setBackground(Color.green);
		checkBoxPanel.add(bold);
		checkBoxPanel.add(italic);
		
		primary.add(display);
		primary.add(radioButtonsPanel);
		primary.add(checkBoxPanel);
		
		//Add Action Listener To test Radio Buttons
		funnyQuote.addActionListener(new ActionListen());
		seriousQuote.addActionListener(new ActionListen());
		politicalQuote.addActionListener(new ActionListen());
		
		//Add Item Listener to test Radio Buttons
		funnyQuote.addItemListener(new ItemListen());
		seriousQuote.addItemListener(new ItemListen());
		politicalQuote.addItemListener(new ItemListen());
		
		//Add Action Listener to test Check Boxes
		bold.addActionListener(new ActionListen());
		italic.addActionListener(new ActionListen());
		
		//Add Item Listener to test Check Boxes
		bold.addItemListener(new ItemListen());
		italic.addItemListener(new ItemListen());
		
		//adds primary JPanel to this JPanel Object
		add(primary);	
	}
	
	private class ActionListen implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			
		 /*
		 Different Get Methods from  ItemEvent 
		 e.getWhen()
		 e.getModifiers()
		 e.getActionCommand()*/
		 
			/*int font=Font.PLAIN;
			if(bold.isSelected()){
				font += Font.BOLD;
			}
			if(italic.isSelected()){
				font += Font.ITALIC;
			}
			display.setFont(new Font("Ariel",font,20));
			
			if(funnyQuote.isSelected()){
				display.setText(funny);
			}
			if(seriousQuote.isSelected()){
				display.setText(serious);
			}
			if(politicalQuote.isSelected()){
				display.setText(political);
			}*/
		}
	}
	private class ItemListen implements ItemListener {

		public void itemStateChanged(ItemEvent arg0) {
			
			/*
			Different Get Methods from ActionEvent
			arg0.getItemSelectable()
			arg0.getStateChange()
			arg0.getItem()*/
			
			
			int font=Font.PLAIN;
			if(bold.isSelected()){
				font += Font.BOLD;
			}
			if(italic.isSelected()){
    			font += Font.ITALIC;
	    	}
		    display.setFont(new Font("Ariel",font,20));
			
			if(funnyQuote.isSelected()){
				display.setText(funny);
			}
			if(seriousQuote.isSelected()){
				display.setText(serious);
			}
			if(politicalQuote.isSelected()){
				display.setText(political);
			}
			
		}
		
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTU_HEO DAKAIView Question on Stackoverflow
Solution 1 - JavaNiranjanBhatView Answer on Stackoverflow
Solution 2 - JavaJavaTechnicalView Answer on Stackoverflow
Solution 3 - JavatrashgodView Answer on Stackoverflow
Solution 4 - JavamariotossView Answer on Stackoverflow
Solution 5 - JavamaximusgView Answer on Stackoverflow