The
check box provides a way to make a single selection switch; it includes a small box and a label. A typical check box has a small "X" (or other type it sets) or is empty, depending on whether the item is selected for decision.
We use the Builder to create a normal check box and use its label to act as its own variable. If we want to read or change it after we create the check box, we can get and set its state, and also get and set its label. Note that the capitalization of the check box is inconsistent with other controls.
Whenever a check box can set and clear an event instruction, we can capture the same method to make a button. In the example below, use a text area to enumerate all the selected check boxes:
: Checkbox1.java
//Using check boxes
import java.awt.*;
Import java.applet.*;
public class CheckBox1 extends Applet {
TextArea t = new TextArea (6);
CheckBox CB1 = new CheckBox ("Check Box 1");
CheckBox CB2 = new CheckBox ("Check Box 2");
CheckBox cb3 = new CheckBox ("Check Box 3");
public void init () {
Add (t); add (CB1); add (CB2); add (CB3);
}
Public boolean action (Event evt, Object Arg) {
if (evt.target.equals (CB1))
Trace ("1", cb1.getstate ());
else if (evt.target.equals (CB2))
Trace ("2", Cb2.getstate ());
else if (evt.target.equals (CB3))
Trace ("3", Cb3.getstate ());
else return
super.action (EVT, arg);
return true;
}
void Trace (String B, Boolean state) {
if (state)
t.appendtext ("box" + B + "set\n");
else
t.appendtext ("box" + B + "cleared\n");
}
///:~
The trace () method sends the selected checkbox name and current state to the text area with AppendText (), so we see a cumulative list of selected check boxes and their status.