Check boxes

Bruce Eckel’s Thinking in Java Contents | Prev | Next

A
check box provides a way to make a single on-off choice; it consists of a tiny
box and a label. The box typically holds a little ‘x’ (or some
other indication that it is set) or is empty depending on whether that item was
selected.

Whenever
a
Checkbox
is set or cleared an event occurs, which you can capture the same way you do a
button. The following example uses a
TextArea
to enumerate all the check boxes that have been checked:

//: CheckBox1.java
// Using check boxes
import java.awt.*;
import java.applet.*;
 
public class CheckBox1 extends Applet {
  TextArea t = new TextArea(6, 20);
  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 + " Setn");
    else
      t.appendText("Box " + b + " Clearedn");
  }
} ///:~ 

The
trace( )
method sends the name of the selected
Checkbox
and its current state to the
TextArea
using appendText( )
so you’ll see a cumulative list of the checkboxes that were selected and
what their state is.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read