import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CheckBoxExample implements ItemListener { private static JFrame frame; private static JPanel panel; private static JCheckBox checkBox; public static void main(String[] args) { frame = new JFrame("Checkbox Example"); panel = new JPanel(); checkBox = new JCheckBox("Select me"); checkBox.addItemListener(new CheckBoxExample()); panel.add(checkBox); frame.add(panel); frame.pack(); frame.setVisible(true); } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { System.out.println("Checkbox is selected"); } else { System.out.println("Checkbox is deselected"); } } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CheckBoxExample implements ItemListener { private static JFrame frame; private static JPanel panel; private static JCheckBox checkBox1; private static JCheckBox checkBox2; public static void main(String[] args) { frame = new JFrame("Checkbox Example"); panel = new JPanel(new GridLayout(2, 1)); checkBox1 = new JCheckBox("Option 1"); checkBox2 = new JCheckBox("Option 2"); checkBox1.addItemListener(new CheckBoxExample()); checkBox2.addItemListener(new CheckBoxExample()); panel.add(checkBox1); panel.add(checkBox2); frame.add(panel); frame.pack(); frame.setVisible(true); } public void itemStateChanged(ItemEvent e) { if (e.getItem() == checkBox1) { if (checkBox1.isSelected()) { System.out.println("Option 1 is selected"); } else { System.out.println("Option 1 is deselected"); } } else if (e.getItem() == checkBox2) { if (checkBox2.isSelected()) { System.out.println("Option 2 is selected"); } else { System.out.println("Option 2 is deselected"); } } } }In this example, two JCheckBoxes are created and added to a JPanel with a GridLayout. An ItemListener is added to each Checkbox using the addItemListener() method. When the state of either Checkbox changes, the itemStateChanged() method is called and outputs a message to the console based on which Checkbox changed. Package library: javax.swing