CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in
which one and only one check box in the group can be checked at any one time.
These check boxes are often called radio
buttons, because they act like the station selector on a car radio—only one
station can be selected at any one
time. To create a set of mutually exclusive check boxes, you must first define
the group to which they will belong and then specify that group when you
construct the check boxes. Check box groups are objects of type CheckboxGroup. Only the default
constructor is defined, which creates an empty group.
You can determine which check box in a group is currently selected
by calling getSelectedCheckbox( ).
You can set a check box by calling
setSelectedCheckbox( ). These
methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Here, which is the check
box that you want to be selected. The previously selected check box will be
turned off.
Here is a program that uses check boxes that are part of a group:
//
Demonstrate check box group.
import
java.awt.*;
import
java.awt.event.*; import java.applet.*; /*
<applet
code="CBGroup" width=240 height=200> </applet>
*/
public
class CBGroup extends Applet implements ItemListener { String msg =
"";
Checkbox
windows, android, solaris, mac; CheckboxGroup cbg;
public void init() {
cbg = newCheckboxGroup();
windows = new Checkbox("Windows",
cbg, true);
android = new Checkbox("Android",
cbg, false);
solaris = new Checkbox("Solaris",
cbg, false);
mac = new Checkbox("Mac OS", cbg,
false);
add(windows);
add(android);
add(solaris);
add(mac);
windows.addItemListener(this);
android.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public
void itemStateChanged(ItemEvent ie) { repaint();
}
//
Display current state of the check boxes.
public
void paint(Graphics g) {
msg =
"Current selection: ";
msg +=
cbg.getSelectedCheckbox().getLabel(); g.drawString(msg, 6, 100);
}
}
Sample output generated by the CBGroup
applet is shown in Figure 26-3. Notice that the check boxes are now circular in
shape.
Figure 26-3 Sample output from the CBGroup applet
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.