Java Reference
In-Depth Information
Example 14−3: YesNoPanel.java (continued)
/** Send an event to all registered listeners */
public void fireEvent(AnswerEvent e) {
// Make a copy of the list and fire the events using that copy.
// This means that listeners can be added or removed from the original
// list in response to this event. We ought to be able to just use an
// enumeration for the vector, but that doesn't actually copy the list.
Vector list = (Vector) listeners.clone();
for(int i = 0; i < list.size(); i++) {
AnswerListener listener = (AnswerListener)list.elementAt(i);
switch(e.getID()) {
case AnswerEvent.YES: listener.yes(e); break;
case AnswerEvent.NO: listener.no(e); break;
case AnswerEvent.CANCEL: listener.cancel(e); break;
}
}
}
/** A main method that demonstrates the class */
public static void main(String[] args) {
// Create an instance of InfoPanel, with title and message specified:
YesNoPanel p = new YesNoPanel("Do you really want to quit?");
// Register an action listener for the Panel. This one just prints
// the results out to the console.
p.addAnswerListener(new AnswerListener() {
public void yes(AnswerEvent e) { System.exit(0); }
public void no(AnswerEvent e) { System.out.println("No"); }
public void cancel(AnswerEvent e) {
System.out.println("Cancel");
}
});
Frame f = new Frame();
f.add(p);
f.pack();
f.setVisible(true);
}
}
Custom Events
Beans can use the standard event types defined in the java.awt.event and
javax.swing.event packages, but they don't have to. Our YesNoPanel class
defines its own event type, AnswerEvent . Defining a new event class is really quite
simple; AnswerEvent is shown in Example 14-4.
Example 14−4: AnswerEvent.java
package com.davidflanagan.examples.beans;
/**
* The YesNoPanel class fires an event of this type when the user clicks one
* of its buttons. The id field specifies which button the user pressed.
**/
public class AnswerEvent extends java.util.EventObject {
public static final int YES = 0, NO = 1, CANCEL = 2; // Button constants
Search WWH ::




Custom Search