Checkboxes and radio buttons look different. Even though radio buttons are made up of checkboxes, they're called radio buttons because that's what they're called in most current GUIs. The only functional difference is that only one of the items in a radio button group can be selected at one time, like the buttons on your car radio. This is useful when you want your user to select one of a set of options. The AWT creates a radio button group by associating a CheckboxGroup instance with all the checkboxes in the group, as shown in Listing 17.19.
Listing 17.19. Creating a radio button group.
import java.awt.*;import java.applet.Applet;public class radio_buttons extends Applet{public void init(){CheckboxGroup group;Checkbox box_1,box_2,box_3;CheckboxGroup group_1;Checkbox box_1_1,box_2_1,box_3_1;//set up the first radio button groupgroup = new CheckboxGroup();box_1 = new Checkbox("Yes", group, true);box_2 = new Checkbox("No", group, false);box_3 = new Checkbox("Maybe", group, false);//set up the second groupgroup_1 = new CheckboxGroup();box_1_1 = new Checkbox("Yes", group_1, false);box_2_1 = new Checkbox("No", group_1, false);box_3_1 = new Checkbox("Maybe", group_1, false);//add the components to the applet paneladd(box_1);add(box_2);add(box_3);add(box_1_1);add(box_2_1);add(box_3_1);}}
The first thing to note is that the second group doesn't have any button selected. That's because none of them were created with a checked state. As soon as the user clicks one of them, though, it won't be possible to return all of them to the unchecked state. Clicking a selected item, such as Yes in the first group, does not change its state to unchecked. Selecting one of the other buttons in the first group deselects Yes and selects the button you clicked.
Radio buttons have only one creator method: new Checkbox(String the_label, CheckboxGroup a_group, boolean checked?)This creates a new Checkbox that is labeled and checked. The middle argument defines which radio button group the checkbox belongs to.
In order to use radio buttons, you also need to create a new checkbox group. Use this code:
new CheckboxGroup()Because radio buttons are implemented as checkboxes, the methods described in the "Checkboxes" section are the ones you'll use to get and set information.
No comments:
Post a Comment