JCheckBox is a Swing component that represents an item which shows a state of selected or unselected. User can change this state by clicking on the check box of the component. Here is a typical JCheckBox component in default Java look and feel:

 a typical Swing JCheckbox

A standard JCheckBox component contains a check box and a label that describes purpose of the check box. An icon and mnemonic key also can be set for this component.

This article describes how to use JCheckBox component in Swing applications, including code examples, common practices and a demo program.

Table of content:

    1. Creating a new JCheckBox object
    2. Adding the check box to a container
    3. Setting and getting selected state
    4. Adding event listeners
    5. Customizing appearance
    6. A demo program for JCheckBox

The following code snippet shows a typical usage of JCheckBox component:

JCheckBox checkbox = new JCheckBox("Enable logging");

// add to a container
frame.add(checkbox);

// set state
checkbox.setSelected(true);

// check state
if (checkbox.isSelected()) {

	// do something...

} else {

	// do something else...

}

Let’s take a closer look at the common practices and examples.

 

1. Creating a new JCheckBox object

According to Javadoc, the JCheckBox class extends from AbstractButton and JToggleButton classes so it has all characteristics of common button as well as two-state (toggle) button.

  • Creating a simplest JCheckBox with only unselected check box without text and icon:
JCheckBox checkbox = new JCheckBox();

Image: a simplest checkbox

When creating new objects of the JCheckBox class, we can specify text, icon, and selected state in any combination of them. Here are some examples:

  • Creating a JCheckBoxwith only text:
    JCheckBox checkbox = new JCheckBox("Enable logging");

    Image: a checkbox with text
  • Creating a JCheckBoxwith only icon:
    JCheckBox checkbox = new JCheckBox(new ImageIcon("images/mail.png"));

    Image: a checkbox with icon

    NOTES: Because the icon replaces the default check box, so using icon for a JCheckBox is not common.

     
  • Creating a JCheckBox with text and selected state:
JCheckBox checkbox = new JCheckBox("Enable logging", true);


Image: a checkbox with text and selected

The text, icon and selected state can be set later, for example:

JCheckBox checkbox = new JCheckBox();

checkbox.setText("Enable logging");
checkbox.setSelected(true);
checkbox.setIcon(icon);

We can also pass an action class to the JCheckBox’s constructor to handle its state and clicking event:

JCheckBox checkbox = new JCheckBox(new CheckboxAction("Enable logging"));

Code of the action class:

class CheckboxAction extends AbstractAction {
	public CheckboxAction(String text) {
		super(text);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JCheckBox cbLog = (JCheckBox) e.getSource();
		if (cbLog.isSelected()) {
			System.out.println("Logging is enabled");
		} else {
			System.out.println("Logging is disabled");
		}
	}
}

Using an action class would be useful in case we have a group of items that does the same action, such as menu item, button and check box.

 

2. Adding the check box to a container

  • A JCheckBox component can be added to a container like JFrame or JPanel:
    frame.add(checkbox);
    panel.add(checkbox); 
  • Adding to a frame with BorderLayout:
    frame.add(checkbox, BorderLayout.CENTER); 
  • Adding to a frame with GridBagLayout:
GridBagConstraints constraints = new GridBagConstraints();
// set constraints...

frame.add(checkbox, constraints); 

 

3. Setting and getting selected state for JCheckBox

Setting state for the check box:

checkbox.setSelected(true);

checkbox.setSelected(false); 

Getting state of the check box:

if (checkbox.isSelected()) {

	// selected, do something...

} else {

	// un-selected, do something else...

} 

 

4. Adding event listeners for JCheckBox

The most interested action of the check box is the clicking event. We can specify a handler for the check box’s clicking event either by adding an action listener or setting an action handler.

  • Adding an action listener:
    checkbox.addActionListener(new ActionListener() {
    	@Override
    	public void actionPerformed(ActionEvent event) {
    		JCheckBox cb = (JCheckBox) event.getSource();
    		if (cb.isSelected()) {
    			// do something if check box is selected
    		} else {
    			// check box is unselected, do something else
    		}
    	}
    }); 
  • Setting an action handler:
AbstractAction actionHandler = new CheckboxAction("Enable logging");
checkbox.setAction(actionHandler); 

Code of the action handler class:

class CheckboxAction extends AbstractAction {
	public CheckboxAction(String text) {
		super(text);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		JCheckBox cbLog = (JCheckBox) event.getSource();
		if (cbLog.isSelected()) {
			System.out.println("Logging is enabled");
		} else {
			System.out.println("Logging is disabled");
		}
	}
}

If we have a group of check boxes and want to use only one action listener for all check boxes:

JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");

// add these check boxes to the container...

// add an action listener
ActionListener actionListener = new ActionHandler();
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);

// code of the action listener class

class ActionHandler implements ActionListener {
	@Override
	public void actionPerformed(ActionEvent event) {
		JCheckBox checkbox = (JCheckBox) event.getSource();
		if (checkbox == checkboxOne) {
			System.out.println("Checkbox #1 is clicked");
		} else if (checkbox == checkboxTwo) {
			System.out.println("Checkbox #2 is clicked");
		} else if (checkbox == checkboxThree) {
			System.out.println("Checkbox #3 is clicked");
		}
	}
}

NOTES: Do not use one action (the class that extends from AbstractActionclass) for a group of check boxes, because the action class will set same state and attributes for all the check boxes. So using an action listener is the recommended practice. 

 

5. Customizing appearance for JCheckBox

  • Setting tooltip text:
    checkbox.setToolTipText("If enabled, write debuggin information to log files.");

    Image: tooltip text for check box

     

  • Setting font style, background color and foreground color:
    checkbox.setFont(new java.awt.Font("Arial", Font.BOLD, 14));
    checkbox.setBackground(Color.BLUE);
    checkbox.setForeground(Color.YELLOW);

    Image: a customized check box

     

  • Setting mnemonic key:
checkbox.setMnemonic('E');

That makes the letter E in the text underlined, so the user can check/uncheck this check box by pressing Alt + E.

Image: a check box with mnemonic key

 

6. A demo program for JCheckBox

Following is a demo program that displays three check boxes which allow the user selecting up to three numbers and calculates the sum:

swing jcheckbox demo program

You can download source code and executable jar file for this demo program in the attachments section.

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (SwingJCheckBoxDemo.zip)SwingJCheckBoxDemo.zip[Demo program for JCheckBox]9 kB

Add comment

   


Comments 

#6Miguel Pulgaron2022-11-15 18:56
OK I need the example for checking mine
Quote
#5Tilen2018-07-29 13:47
When I copy -> paste in java writer
this code its give my code
diagnostic to I must change the
code. Its give me this:
JCheckBox cannot be resolved
to a type (two times) and
frame cannot be resolved.
Why?
Quote
#4Nam2018-05-05 22:37
Hi Zohair Ali,
Please send the relevant code so I can help.
Quote
#3Zohair Ali2018-05-04 18:15
Hi My name is Zohair Ali.
im Working on food ordering system My problem is that when i checkbox any of the item text box of that is enable but like i write quantity as "1" in total text field its not showing anything .i am having problem in totaling the cost of items.
Quote
#2Nam2016-05-23 04:19
Quoting manoj:
Hi,
I got a problem on retrieving the text of checkbox onto the label in swing.
Please tell me the process for above problem.

Thank you,
Manoj


Sorry, I don't understand what you mean?
Quote