isSelected() - Getting State of Check Box

This section provides a tutorial example on how to use the isSelected() method to know the state of a check box.

If you are using multiple check boxes, you need to keep track of them and use the isSelected() method to get the state of each of them. Here is a sample program:

 * Copyright (c) All Rights Reserved.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBoxAction implements ActionListener {
   JCheckBox red; 
   JCheckBox green; 
   JCheckBox blue;
   JLabel myLabel = null;
   public static void main(String[] a) {
      JCheckBoxAction myTest = new JCheckBoxAction();
   public void createFrame() {
      JFrame f = new JFrame("My Check Boxes");
      Container c = f.getContentPane();
      c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3,1));

	  red = new JCheckBox("Red");
      green = new JCheckBox("Green");
      blue = new JCheckBox("Blue");
      JButton b = new JButton("Done");
      myLabel = new JLabel("Please select",SwingConstants.CENTER);
   public void actionPerformed(ActionEvent e) {
	  String t = "";
	  if (red.isSelected()) t += "Red ";
	  if (green.isSelected()) t += "Green ";
	  if (blue.isSelected()) t += "Blue ";
	  if (t.equals("")) t = "Nothing selected";

If you run this program, you will see none of the check boxes is selected initially. If you click "Done", you will get the "Nothing selected" message. If you select some check boxes, then click "Done", you will get all selected items:

JCheckBox Selected Items
JCheckBox Selected Items

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

JCheckBox - Swing Check Box Class

 javax.swing.JCheckBox and Related Methods

 ActionListener, ChangeListener and ItemListener

isSelected() - Getting State of Check Box

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Outdated Tutorials


 Full Version in PDF/EPUB