JCheckBox Example
This JCheckBox example allows a two-way choice for the user. Unlike radio buttons, of which only one is chosen, as many JCheckBox items can be checked/ticked as required (a JCheckBox is also called a tick box).
In this JCheckBox example a user is asked to tick those JCheckBoxes that are appropriate.
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
// JCheckBox Example
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
class JCheckBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
Box box = new Box(BoxLayout.Y_AXIS);
cp.add(box);
box.add(new JLabel("Tick the sports you like..."));
String[] sports = {"Football", "Rugby", "Cricket", "Badminton", "Baseball"};
JCheckBox[] cba = new JCheckBox[sports.length];
for (int i = 0; i < sports.length; i++) {
cba[i] = new JCheckBox(sports[i]);
box.add(cba[i]);
cba[i].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox jCheckBox = (JCheckBox)e.getSource();
if(jCheckBox.isSelected())
System.out.println(jCheckBox.getText() + " selected");
else
System.out.println(jCheckBox.getText() + " deselected");
}
});
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
18-19 String and JCheckBox arrays are created.
21-33 A loop is used to initialize each JCheckBox, add to the frame, and add an ItemListener.
26-30 When a user event happens the JCheckBox is identified, and whether the JCheckBox is selected or deselected is reported.
