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 {
TextField t;
float price = 7.00f;
public void init() {
Checkbox c;
this.add(new Label("What do you want on your pizza?", Label.CENTER));
this.t = new TextField(String.valueOf(price));
// so people can't change the price of the pizza
t.setEditable(false);
Pricer p = new Pricer(price, t);
c = new Checkbox("Pepperoni");
this.add(c);
c.addItemListener(p);
c = new Checkbox("Olives");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Onions");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Sausage");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Peppers");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Extra Cheese");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Ham");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Pineapple");
c.addItemListener(p);
this.add(c);
c = new Checkbox("Anchovies");
c.addItemListener(p);
this.add(c);
this.add(t);
}
}
class Pricer implements ItemListener {
TextField out;
double price;
public Pricer(double baseprice, TextField out) {
this.price = baseprice;
this.out = out;
}
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) this.price += 0.50f;
else this.price -= 0.50f;
// Change the price
this.out.setText(String.valueOf(price));
}
}