13.4 Checkboxes

This section describes checkboxes (toggle buttons) that operate independently of other checkboxes. In the next section, I'll show how to put checkboxes into a group so that they operate like radio buttons (where pressing one raises the previous selection). The most common usage is to create one with a specified label and then drop it into a window. You can watch for action events in Java 1.0, item selection events in Java 1.1, or simply wait until you need the value then look it up via getState. Creating a checkbox and placing it in a nested window would look something like the following:

      Checkbox cb = new Checkbox("...");
      somePanel.add(cb);

Constructors

These three constructors apply to checkboxes that operate independently of each other. The following section will introduce two more that are used with radio buttons.

public Checkbox(String checkboxLabel)

This creates a checkbox with the specified label. It is initially unchecked; see setState for changing it.

public Checkbox()

This creates an initially unchecked checkbox with no label.

public Checkbox(String checkboxLabel, boolean state) [Java 1.1]

This creates a checkbox with the specified label. It can be checked or unchecked depending on the boolean value provided. A value of true means it is checked.

Example

Listing 13.15 creates twelve checkboxes, placing them in a two-column layout with the even-numbered ones initially checked. Figure 13-10 shows the result on Windows 95. For examples in MacOS and Unix/X, see Section 13.5, "Checkbox Groups (Radio Buttons)."

Listing 13.15 Checkboxes.java

import java.awt.*

public class Checkboxes extends QuittableFrame {
  public static void main(String[] args) {
    new Checkboxes();
  }

  public Checkboxes() {
    super("Checkboxes");
    setFont(new Font("Helvetica", Font.BOLD, 18));
    setLayout(new GridLayout(0, 2));
    Checkbox box;
    for(int i=0; i<12; i++) {
      box = new Checkbox("Checkbox " + i);
      if (i%2 == 0)
        box.setState(true);
      add(box);
    }
    pack();
    show();
  }
}

Figure 13-10 Checkboxes in Java.



Other Checkbox Methods

public boolean getState()

This determines if the checkbox is checked (true) or unchecked (false).

public void setState(boolean checkedState)

This method sets the checkbox to be checked (true) or unchecked (false).

public String getLabel()

This retrieves the current label.

public void setLabel(String newLabel)

The setLabel method changes the label. As with buttons, if the checkbox is already displayed, doing this does not automatically resize it in its Container. So the containing window should be invalidated and validated to force a new layout, as illustrated here:

      someCheckbox.setLabel("A New Label");
      someCheckbox.getParent().invalidate();
      someCheckbox.getParent().validate();

public void addItemListener(ItemListener listener) [Java 1.1]
public void removeItemListener(ItemListener listener) [Java 1.1]

These methods associate or unassociate ItemListeners with the checkbox. They are discussed further in the following subsection.

public void processItemEvent(ItemEvent event) [Java 1.1]

This is a lower-level event-processing method. If you use this, enable events first and call super.processItemEvent from within the method. See the following subsection for details.

public Object[] getSelectedObjects() [Java 1.1]

This method returns an array containing a single item: either the checkbox label (if the checkbox is checked) or null (if unchecked).

Like the other GUI controls, Checkbox inherits all of the Component methods listed in Section 11.2. However, the foreground color (setForeground) is implemented inconsistently on Windows 95 and MacOS. For instance, JDK 1.02, Netscape 2.02, and Internet Explorer 3.01 support background but not foreground colors for checkboxes on Windows 95. JDK 1.1, Netscape 3.01, and Netscape 4.01 support both foreground and background colors on Windows. Netscape 3 supports background but not foreground colors on MacOS.

Core Warning


Many Windows and Mac implementations ignore foreground colors for checkboxes.


Handling Events

Checkbox Events in Java 1.0

In Java 1.02, checkboxes generate action events when selected or deselected. You can process these events in the checkbox or in the enclosing window, just as with buttons. You can check the status of a checkbox by looking at the result of the getState method. Alternatively, the second argument to action is a Boolean (not boolean) representing the current state, but using it adds little if any benefit over simply checking the state with getState. For instance, to process events in the Container, you might do something like the following:

      public boolean action(Event event, Object object) {
        if (event.target == checkbox1) {
          if (checkbox1.getState()) {
            doActionForCheckedBox();
            return(true);
          } else {
            doActionForUncheckedBox();
            return(true);
          }
        } ...
      }

It is also common to ignore the action event when it occurs, and simply look up the status of the Checkbox (using getState) when it is needed. Other times, however, you want to take action immediately. For instance, a GUI might present some image-editing options, and the checkbox might allow the user to specify whether or not the image is in color. In such a case, you might want to enable the color palette when the checkbox is selected and disable the palette when the checkbox is deselected.

Checkbox Events in Java 1.1

In JDK 1.1, checkboxes do not generate action events. They generate item-selection events instead. To handle events in the checkbox itself, you first enable events:

      enableEvents(AWTEvent.ITEM_EVENT_MASK);

Next, you override processItemEvent, which takes an ItemEvent as an argument. You should call super.processItemEvent in the body of processItemEvent in case any ItemListeners have been attached. The ItemEvent class has two useful methods above and beyond those in the AWTEvent class: getItemSelectable and getStateChange. The first of these returns the checkbox as an ItemSelectable (an interface Checkbox implements), while the second returns either ItemEvent.SELECTED or ItemEvent.DESELECTED.

To process events in another object, attach an ItemListener to the checkbox via addItemListener. An ItemListener must implement the itemStateChanged method, which takes an ItemEvent as an argument.


Continue to Section 13.5 (Checkbox Groups (Radio Buttons)). Return to Chapter 13 table of contents.