In java.awt we are not having a special class for radio buttons but we can create radio button from Checkbox class. Radio buttons are created as instances of the CheckboxGroup class. The object of
CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in "on" state and remaining check box button in "off" state.
public class CheckboxGroup extends Object implements Serializable
Steps for converting checkboxes into radiobutton:
1. Create objects of CheckboxGroup class.
Ex: CheckboxGroup cbg1=new CheckboxGroup ();
2. Create 'n' number of objects of Checkbox class.
Ex:
Checkbox b1, b2, b3;
b1=new Checkbox ("C");
b2=new Checkbox ("Cpp");
b3=new Checkbox ("Java");
3. Decide which checkboxes are adding to which CheckboxGroup object. In order to add the checkboxes to the CheckboxGroup object, in Check box class we have the following method:
public void setCheckboxGroup (CheckboxGroup);
Ex:
cb1.setCheckboxGroup (cbg1);
cb2.setCheckboxGroup (cbg2);
cb3.setCheckboxGroup (cbg3);
Instead of using a setCheckboxGroup method the following Constructor which is present in Check box class can be used to create checkbox group.
Checkbox (String, CheckboxGroup, boolean);
Checkbox (String, boolean, CheckboxGroup);
Ex:
Checkbox cb1=new Checkbox ("C", cbg1, false);
Checkbox cb2=new Checkbox ("Cpp", cbg2, false);
Checkbox cb3=new Checkbox ("Java", cbg3, false);
Ex:
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Cpp", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { label.setText("C++ checkbox: Checked"); } });
checkBox2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) {label.setText("Java checkbox: Checked"); } });
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
0 comments:
Post a Comment