R4R
Right Place For Right Person TM
 

R4R JAVAAWT Examples Handling Checkbox Group in java

previous

Home

Next

Handling Checkbox Group in java

In this example we are going to Handle CheckboxGroup.CheckboxGroup is use to create mutually exclusive checkbox in which one and only one checkbox in a group is selected at any one time. these Checkbox are also called Radio button

To Handle the CheckboxGroup we are using three type of package. One is java.awt.* second is  java.applet.* and third is java.awt.event.*; .The java.awt.* is used for GUI interface. AWT classes are contain in this package. The  java.applet.* package is used to create an applet and java.awt.event.*; defined within the java.awt.*; package is a subclass of EventObject. It is a super class of all AWT-based event..

Checkbox support these constructors:
Checkbox (String str, boolen on, CheckboxGroup cbGroup);
Checkbox(String str, CheckboxGroup cbGroup,  Boolean on,);
In both constructor the label is defined by str and whose group is specified by cbGoup. The value of on determine the initial state of CheckboxGroupIn our example first we implement IctionListener() each listener implement the IctionLinstner.
When an event is occur itemStateChange() interface is called. An ItemEventobject is supplied as the argument to this method.
To determine which Checkbox in a Group is currently selected we call method:



Checkbox getSelectedCheckbox()
You can set a CheckboxGroup by  calling:
void setSelectedCheckbox(Checkbox which);  which denote the check box that you want to selected.
In our example there are two radio button one is male and other is female. At one time only one item is selected.

//creat CheckboxGroup
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckBoxGroup" width=300 height=200>
</applet>
*/
public class CheckBoxGroup extends Applet implements ItemListener {
String msg="";
Checkbox one,two;
CheckboxGroup cbg;
public void init(){
 cbg=new CheckboxGroup();
 one = new Checkbox("Male",cbg,true);
 two = new Checkbox("Female",cbg,false);
add(one);
add(two);
one.addItemListener(this);
two.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
repaint();
}
public void paint(Graphics g){
msg="Your gender is....";
g.drawString(msg,4,80);
msg = cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,4,120);
}
}

Download Source Code

Output Of Example

previous

Home

Next

New Updates

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R