Using Radio Buttons in AWT



There will be times when you want the user to select among several values, or you want to keep track of “on” and “off” values for a specific attribute. This is where radio buttons (you may call them check boxes) come in handy. Radio buttons differ from regular buttons in that interaction with radio buttons is not caught by the ActionListener interface. Instead, your applet must implement the ItemListener interface. Much like the ActionListener interface, the ItemListener interface defines a single method, in this case the itemStateChanged method, which takes an ItemEvent as its parameter.

Radio buttons can be added to your applets singularly or within button groups. To allow the user to toggle the sound on or off, you may use a single radio button. To create such a labeled radio button initially set to “on,” type the following:

Checkbox sound = new Checkbox("Enable Sound", true);

To access the state of a radio button, you can use the getState method, such as the following:

boolean soundEnabled = sound.getState();

Another way to use radio buttons is within button groups. Button groups preserve the idea of a single selection within the group. When a member of the group is toggled “on,” all other buttons within the group is automatically toggled “off.” Use this when your applet requires only one of a group of items to be active. The Java CheckboxGroup class is used to hold a group of radio buttons. The following program, CheckboxTest, uses a CheckboxGroup to hold a number of selections. Each time a different item is selected, a message is printed to the console.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CheckboxTest extends Applet implements ItemListener
{
// a CheckboxGroup to hold a number of items
private CheckboxGroup cbg;
// selections used by the applet
private final String selections[] = {"Pepsi", "Coke", "Mountain Dew", "Tab"};
private Checkbox createCheckbox(
String label, // label for Checkbox
CheckboxGroup group, // group Checkbox belongs to
boolean enabled // true to set this Checkbox "on"
)
{
Checkbox cb = new Checkbox(label, group, enabled);
cb.addItemListener(this);
return cb;
}
// this method overrides the init method from the Applet class
public void init()
{
cbg = new CheckboxGroup();
for(int i = 0; i < selections.length; i++)
{
add(createCheckbox(selections[i], cbg, false));
}
}
// implementation of the itemStateChanged method from the ItemListener
// interface
public void itemStateChanged(ItemEvent e)
{
// print out a message about the selection
System.out.println("Yes, I certainly agree, " +
cbg.getSelectedCheckbox().getLabel() +
" is very delicious!");
}
} // CheckboxTest


Note the use of the ItemListener interface and the addItemListener method.