Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

752 Part II: The Java Library


enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Checkbox name/state: " + getLabel() +
"/" + getState());
super.processItemEvent(ie);
}
}
}

Extending Choice

The following program creates an applet that displays a choice list with items labeled “Red”,
“Green”, and “Blue”. When an entry is selected, a string that contains the name of the color
is displayed on the status line of the applet viewer or browser.
There is one top-level class namedChoiceDemo2that extendsApplet. Itsinit( )method
creates a choice element and adds it to the applet.MyChoiceis an inner class that extends
Choice. It callsenableEvents( )so that item events may be received by this object. When an
item event is generated,processItemEvent( )is called. That method displays a string on the
status line and callsprocessItemEvent( )for the superclass.

/*
* <applet code=ChoiceDemo2 width=300 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ChoiceDemo2 extends Applet {
MyChoice choice;
public void init() {
choice = new MyChoice();
choice.add("Red");
choice.add("Green");
choice.add("Blue");
add(choice);
}
class MyChoice extends Choice {
public MyChoice() {
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Choice selection: " + getSelectedItem());
super.processItemEvent(ie);
}
}
}

Extending List

The following program modifies the preceding example so that it uses a list instead of a
choice menu. There is one top-level class namedListDemo2that extendsApplet. Itsinit( )
method creates a list element and adds it to the applet.MyListis an inner class that extends
Free download pdf