Swing JCheckBox Class
Overview
In this tutorial, we will learn how to use Swing JCheckBox Class to create checkboxes. A checkbox GUI component allows users to turn something on and off.
Swing JCheckBox Class
We can use the Swing JCheckBox class to create checkboxes.
The JCheckBox class inherits all functionality of JToogleButton class. The class implements the Accessible interface. We can create a checkbox with text or with an icon or both.
Java Program
package com.testingdocs.swing.components; /********************************************** * FileName: CheckBoxDemo.java * Package : com.testingdocs.swing.components * * Java Tutorials - www.TestingDocs.com **********************************************/ import java.awt.BorderLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class CheckBoxDemo { public static void main(String[] args) { //Create a frame instance JFrame frame = new JFrame("Swing CheckBox - www.TestingDocs.com"); // Create a checkbox instance JCheckBox chkBox = new JCheckBox("Checkbox Example"); chkBox.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { JOptionPane.showMessageDialog(frame, "CheckBox is checked"); } } }); // Create Panel instance JPanel panel = new JPanel(); panel.add(chkBox); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 200); frame.getContentPane().add(panel, BorderLayout.SOUTH); frame.setVisible(true); } }
Output
Run the Java application to view the output.