Creating CheckBox with JCheckBox Class

In this tutorial, you will learn how to use JCheckBox class to create checkboxes.

To create checkboxes, you use the JCheckBox class. The JCheckBox class inherits all functionality of JToogleButton class. A checkbox allows user to turn something on  and off . You can create checkbox with text, icon or both. Here are the most typical constructors of JCheckBox class:

JCheckBox ConstructorsMeanings
public JCheckBox( )Creates a checkbox without text and icon. The state of checkbox is not selected.
public JCheckBox(Icon icon)Creates a checkbox with icon
public JCheckBox(Icon icon, boolean selected)Creates a checkbox with icon and initialize the state of checkbox by the boolean parameter selected
public JCheckBox(String text)Creates a checkbox with text
public JCheckBox(String text, boolean selected)Creates a checkbox with text and initialize  the state of the checkbox
public JCheckBox(String text, Icon icon)Creates a checkbox which displays both text and icon.
public JCheckBox(String text, Icon icon, boolean selected)Creates a checkbox which displays both text and icon. The state of checkbox can be initialized.

There are two ways to work with checkbox’s state:

  • You use addActionListener() or AddItemListener() method so that whenever the state of checkbox change you can have corresponding logic to handle this.
  • Use isSelected() to check whether the checkbox is selected.

JCheckbox Demo Application

In this example, we create a checkbox. When user clicks on it, a message will display to notify the checkbox’s state. Here is the output of the demo application:

JCheckBox

When user checks the checkbox, a message popup will display like the following screenshot:

JCheckBox Demo

Here is the code sample of JCheckBox demo: