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:

/* JCheckBoxAction.java
 * Copyright (c) 1997-2024 HerongYang.com. 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();
      myTest.createFrame();
   }
   public void createFrame() {
      JFrame f = new JFrame("My Check Boxes");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      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");
      p.add(red);
      p.add(green);
      p.add(blue);
    
      c.add(p);
      JButton b = new JButton("Done");
      b.addActionListener(this);
      c.add(b);
      myLabel = new JLabel("Please select",SwingConstants.CENTER);
      c.add(myLabel);
      f.pack();
      f.setVisible(true);
   }
   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";
      myLabel.setText(t);
   }
}

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

 Archived Tutorials

 References

 Full Version in PDF/EPUB