A check box group is a set of checkboxes in which one and only one checkbox can be checked at anyone time. Any other previously selected checkbox in the group is unchecked. These checkboxes are sometimes called radio buttons.
To create a check box group, follow the following steps,
1. Creating a CheckboxGroup object using the following constructor.
CheckboxGroup()
For example, the following statement creates a checkbox group named sex.
CheckboxGroup sex = new CheckboxGroup();
2. Create a Checkbox object: Pass a reference to the CheckboxGroup object to the Checkbox constructor. The Checkbox class provides the following two constructors to include a checkbox in acheckbox group.
Checkbox(String str,boolean state,CheckboxGroup cbgroup)
Checkbox(String str,CheckboxGroup cbGroup,boolean state)
Here, str specifies the label of the associated checkbox, state specifies the initial state of the associated check box, cbgroup is the checkbox group for the associated checkbox or null if the checkbox is not the part of a group.
For example, the following statements add two checkboxes labelled Male and Female to the checkbox group sex.
Checkbox(“Male”,true,sex);
Checkbox(“Female”,false,sex);
In Table we have the main methods of java.awt.CheckboxGroup class.
Method | Description |
CheckboxGroup () | Creates a group of checkboxes. |
getSelectedCheckbox () | Gets the Checkbox component group currently selected. |
setSelectedCheckbox (Checkbox) | Determines which Checkbox component selected group. |
import java.awt.*;
class CheckboxExample extends Frame
{
CheckboxExample()
{
setLayout(new FlowLayout());
Label lblSex = new Label("Sex");
CheckboxGroup sex = new CheckboxGroup();
Checkbox ChkMale = new Checkbox("Male",true,sex);
Checkbox Chkfemale = new Checkbox("Female",false,sex);
add(lblSex);
add(ChkMale);
add(Chkfemale);
}
}
class CheckboxGroupJavaExample
{
public static void main(String args[])
{
CheckboxExample frame = new CheckboxExample();
frame.setTitle("CheckboxGroup Java Example");
frame.setSize(250,100);
frame.setResizable(false);
frame.setVisible(true);
}
}