Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JCheckBox & ItemListener

1. About JCheckBox

Like JToggleButton, JCheckBox is also a two-state information component. It can represent two states. One is Checked State and other one is UnChecked State. In a checked state, the user will see a tick mark and in an unchecked state, there will not be any tick mark. Java Swing check box will produce ItemEvent when user check or uncheck a check box. 

2. About JCheckBox Example

The Example we create here is shown in the below picture:

JCheckBox Example
JCheckBox Example

The example contains three JCheckBox items in the content pane of the JFrame window. It also has a JTextField element. When the user places a checkmark on any of the available checkbox, the JTextField will report that. In the above picture, the text field reports, user placed a check mark on the check box item 2. Now, we will implement this example.

3. Class Data Members

We have a JTextField data members in our class. This member will report the lastly checked checkbox and we will access it while we handle the user action on the check boxes.

4. Create JCheckBox Components

In code snippet 2, we create three JCheckBoxes and we give the checkbox label as string while we construct it. Next, the our snippet creates JTextField with a column width of 35 Characters. After creating these components, we add it to the content pane of the JFrame via the add method.

5. Report Checked CheckBox via ItemListener

The JCheckBox reports the State-Change to the itemStateChanged event handler. We use this handler to check the state of the Checkbox. Note, since we provide an anonymous handler for each check boxes, we no need to find the event source. JCheckBox method isSelected returns true when the user changes the checkbox state from Un-Ticked to Ticked. We use this method and update the JTextField to state which JCheckBox was recently moved to the checked state. 

You can watch this complete example as a Youtube video below.

6. Watch JCheckBox Demo – Youtube

7. Code Reference

Categories: Swing

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.