by Dinesh Thakur Category: Swing

A checkbox component in Swing is similar to checkbox component in AWT. A check box is a control that consists of a combination of a small box and a label. The label provides the description of the box with which it is associated. It is a two-state control having states true (checked) and false (unchecked). The state of a checkbox can be changed by clicking on it. A checkbox is an object of JCheckBox class.

The following table shows some methods of this class:

 

Method

Description

JCheckBox()              

Creates a checkbox without text and not selected

JCheckBox(Str,bool)

Creates a checkbox with the specified text and status

isSelected()            

Returns whether the checkbox is selected (true) or not (false)

setSelected(boolean b)

selects if b is true, and marks it as selected if it is false;

String getText()

it returns the text associated with the JCheckBox. This operation replaces getLabel it has become deprecated;

setEnabled(boolean b)

enable or disable the component so that it can be usable or not by the user.

import javax.swing.*;

import java.awt.*;
class CheckBoxExample extends JFrame
{
   CheckBoxExample()
   {
     setLayout(new FlowLayout());
     JLabel lblHobbies = new JLabel("HOBBIES");
     JCheckBox chkSports = new JCheckBox("Sports");
     JCheckBox chkMusic = new JCheckBox("Music",true);
     JCheckBox chkReading = new JCheckBox("Reading");
     add(lblHobbies);
     add(chkSports);
     add(chkMusic);
     add(chkReading);
   }
}
  class CheckBoxJavaExample
 {
      public static void main(String args[])
     {
             CheckBoxExample frame = new CheckBoxExample();
             frame.setTitle("JCheckBox Java Example");
             frame.setBounds(200,250,350,100);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setResizable(false);
             frame.setVisible(true);
      }
 }

JCheckBox in Java Swing Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article