JCheckbox - Part 2

To make the Checkboxes actually work, we need to add an ItemListener, just like we did for JToggleButton. This is very simple, and works a lot like the ActionListener we used for the JButton.

This means that any time the JCheckBox is selected or deselected by the user, the ItemListener will catch this and throw it to a method called ItemStateChanged(). ItemStateChanged will then change the program however we decide.

Let's see the previous example edited slightly to incorporate the ItemListener.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

public class CheckBoxExample_Extended implements  ItemListener{
    
    JCheckBox redCB, blueCB, greenCB, yellowCB;
    JPanel redBox, blueBox, greenBox, yellowBox;

    public JPanel createContentPane (){
        
        JPanel totalGUI = new JPanel();
        
        // We create four checkboxes to control what is currently on-screen.
        // At the start, we set the red checkbox to 'ticked' or selected.
        // We also add an itemListener for each JCheckBox
        
        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.PAGE_AXIS));
        checkBoxPanel.add(Box.createRigidArea(new Dimension(10,0)));

        redCB = new JCheckBox("Red");
        redCB.setSelected(true);
        redCB.addItemListener(this);
        
        checkBoxPanel.add(redCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        blueCB = new JCheckBox("Blue");
        blueCB.addItemListener(this);
        
        checkBoxPanel.add(blueCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        greenCB = new JCheckBox("Green");
        greenCB.addItemListener(this);
        
        checkBoxPanel.add(greenCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        yellowCB = new JCheckBox("Yellow");
        yellowCB.addItemListener(this);
        
        checkBoxPanel.add(yellowCB);
        checkBoxPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        
        // Now we create a simple JPanel that displays our four coloured boxes.

        JPanel boxPanel = new JPanel(new GridLayout(2, 2, 20, 20));
        
        redBox = createSquareJPanel(Color.red, 50);
        blueBox = createSquareJPanel(Color.blue, 50);
        greenBox = createSquareJPanel(Color.green, 50);
        yellowBox = createSquareJPanel(Color.yellow, 50);
        
        // This sets all bar the red box to be hidden.
  
        blueBox.setVisible(false);
        greenBox.setVisible(false);
        yellowBox.setVisible(false);
        
        boxPanel.add(redBox);
        boxPanel.add(blueBox);
        boxPanel.add(greenBox);
        boxPanel.add(yellowBox);
        
        totalGUI.add(checkBoxPanel);
        totalGUI.add(boxPanel);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // In this method, we create a square JPanel of a colour and set size
    // specified by the arguments.

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }
    
    // In itemStateChanged, we first determine if the item was selected
    // or deselected and set a temporary boolean depending.
    // Then we determine which item it was that was changed and display the 
    // coloured box to match.
    
    public void itemStateChanged(ItemEvent e){
        
        boolean visible = false;
        
        if (e.getStateChange() == ItemEvent.DESELECTED) {
            visible = false;
        }
        else
        {
            visible = true;
        }
        
        if(e.getItemSelectable() == redCB)
        {
            redBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == blueCB)
        {
            blueBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == greenCB)
        {
            greenBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == yellowCB)
        {
            yellowBox.setVisible(visible);
        }
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JCheckBox [=]");

        CheckBoxExample_Extended demo = new CheckBoxExample_Extended();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
CheckBox Example 2

This time, the class implements the ItemListener.
6
public class CheckBoxExample_Extended implements  ItemListener{
Each JCheckBox has an ItemListener attached to it.
25
        redCB.addItemListener(this);
We create the method itemStateChanged to deal with the change in state of the JCheckBoxes and pass the argument in of an ItemEvent. Firstly, we use the .getStateChange() to determine if the event is a selection or de-selection of the JCheckBox. We set a temporary variable depending on its outcome.
96
97
98
99
100
101
102
        if (e.getStateChange() == ItemEvent.DESELECTED) {
            visible = false;
        }
        else
        {
            visible = true;
        }
Then we determine which box was pressed using the e.getItemSelectable() command. Using this information we set the visibility of the corresponding box.
You can get more information for these commands from the Java API
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        if(e.getItemSelectable() == redCB)
        {
            redBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == blueCB)
        {
            blueBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == greenCB)
        {
            greenBox.setVisible(visible);
        }
        else if(e.getItemSelectable() == yellowCB)
        {
            yellowBox.setVisible(visible);
        }
There is another way to find out if a JCheckbox is selected or not, using the .isSelected(); method. You can use the syntax .isSelected(); which will return a boolean depending if it is selected or not. Here's a change to the previous program that only refreshes the box on a button press.

Note the changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

public class CheckBoxExample_UltraExtended implements  ActionListener{
    
    JCheckBox redCB, blueCB, greenCB, yellowCB;
    JPanel redBox, blueBox, greenBox, yellowBox;
    JButton refresh;

    public JPanel createContentPane (){
        
        JPanel totalGUI = new JPanel();
        
        // We create four checkboxes to control what is currently on-screen.
        // At the start, we set the red checkbox to 'ticked' or selected.
        
        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.PAGE_AXIS));
        checkBoxPanel.add(Box.createRigidArea(new Dimension(10,0)));

        redCB = new JCheckBox("Red");
        redCB.setSelected(true);
        
        checkBoxPanel.add(redCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        blueCB = new JCheckBox("Blue");        
        checkBoxPanel.add(blueCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        greenCB = new JCheckBox("Green");
        checkBoxPanel.add(greenCB);
        checkBoxPanel.add(Box.createHorizontalGlue());
        
        yellowCB = new JCheckBox("Yellow");
        checkBoxPanel.add(yellowCB);
        checkBoxPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        
        // Now we create a simple JPanel that displays our four coloured boxes.

        JPanel boxPanel = new JPanel(new GridLayout(2, 2, 20, 20));
        
        redBox = createSquareJPanel(Color.red, 50);
        blueBox = createSquareJPanel(Color.blue, 50);
        greenBox = createSquareJPanel(Color.green, 50);
        yellowBox = createSquareJPanel(Color.yellow, 50);
        
        // This sets all bar the red box to be hidden.
  
        blueBox.setVisible(false);
        greenBox.setVisible(false);
        yellowBox.setVisible(false);
        
        boxPanel.add(redBox);
        boxPanel.add(blueBox);
        boxPanel.add(greenBox);
        boxPanel.add(yellowBox);
        
        // Now lets quickly add a refresh button with an actionListener to determine
		// when it is pressed.
        
        refresh = new JButton("Refresh");
        refresh.addActionListener(this);
        
        totalGUI.add(checkBoxPanel);
        totalGUI.add(boxPanel);
        totalGUI.add(refresh);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // In this method, we create a square JPanel of a colour and set size
    // specified by the arguments.

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }
    
    // This actionPerformed simply takes sets the visibility of each
    // coloured box to the state of each checkbox.
        
    public void actionPerformed(ActionEvent e) {
        
        if(e.getSource() == refresh)
        {
            redBox.setVisible(redCB.isSelected());
            blueBox.setVisible(blueCB.isSelected());
            greenBox.setVisible(greenCB.isSelected());
            yellowBox.setVisible(yellowCB.isSelected());
        }
    }


    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JCheckBox [=]");

        CheckBoxExample_UltraExtended demo = new CheckBoxExample_UltraExtended();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
CheckBox Example 3

Questions

Let's see if you can tick all the boxes.

Question 1. Why must we set the visibility of the JFrame to true?

  • a) Otherwise the JFrame would automatically go to the middle of the screen.
  • b) Otherwise we could not see the JFrame, yet the program would run.
  • c) Otherwise the program would not compile.

Question 2. Which Event Listener does a JCheckBox use?

  • a) ActionListener
  • b) ItemListener
  • c) FormListener

Question 3. How do we find if a JCheckbox is selected without using an event?

  • a) selected();
  • b) wasSelected();
  • c) isSelected();
  • d) couldBeSelected();




Hopefully this gives you a good insight into how to instantiate JCheckBoxes and really bring them to life!.

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict