When the a Checkbox
changes state, normally as a
result of user action, it fires an ItemEvent
. Most of
the time you ignore this event. Instead you manually check the
state of a Checkbox
when you need to know it. However
if you want to know immediately when a Checkbox
changes state, you can register an ItemListener
for
the Checkbox
.
An ItemEvent
is exactly the same as the item event
fired by a Choice
. In fact item events are used to
indicate selections or deselections in any sort of list including
checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the
age-old question, "What do you want on your pizza?" When an
ingredient is checked the price of the pizza goes up by fifty
cents. When an ingredient is unchecked fifty cents is taken off.
The price is shown in a TextField
.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Ingredients extends Applet {
private TextField display;
private double price = 7.00;
public void init() {
this.add(new Label("What do you want on your pizza?", Label.CENTER));
Pricer p = new Pricer(this);
Checkbox pepperoni = new Checkbox("Pepperoni");
this.add(pepperoni);
pepperoni.addItemListener(p);
Checkbox olives = new Checkbox("Olives");
olives.addItemListener(p);
this.add(olives);
Checkbox onions = new Checkbox("Onions");
onions.addItemListener(p);
this.add(onions);
Checkbox sausage = new Checkbox("Sausage");
sausage.addItemListener(p);
this.add(sausage);
Checkbox peppers = new Checkbox("Peppers");
peppers.addItemListener(p);
this.add(peppers);
Checkbox extraCheese = new Checkbox("Extra Cheese");
extraCheese.addItemListener(p);
this.add(extraCheese);
Checkbox ham = new Checkbox("Ham");
ham.addItemListener(p);
this.add(ham);
Checkbox pineapple = new Checkbox("Pineapple");
pineapple.addItemListener(p);
this.add(pineapplec);
Checkbox anchovies = new Checkbox("Anchovies");
anchovies.addItemListener(p);
this.add(anchovies);
this.display = new TextField(String.valueOf(price));
// so people can't change the price of the pizza
display.setEditable(false);
this.add(display);
}
public void setPrice(double price) {
this.price = price;
display.setText(String.valueOf(price));
}
public double getPrice() {
return this.price;
}
}
class Pricer implements ItemListener {
private Ingredients out;
public Pricer(Ingredients out) {
this.out = out;
}
public void itemStateChanged(ItemEvent ie) {
double price = out.getPrice();
if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;
else price -= 0.50;
// Change the price
out.setPrice(price);
}
}