One benefit of the
New AWT event model is flexibility. In the old model we were forced to write code hard for our program. But the new model we can invoke to add and delete event actions in a single method. The following example demonstrates this:
: Dynamicevents.java//The new Java 1.1 event model allows to//change event behavior dynamically.
Also//Demonstrates multiple actions for an event.
Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;
public class Dynamicevents extends Frame {vector v = new vector ();
int i = 0;
Button B1 = New button ("button 1"), B2 = New button ("button 2");
Public dynamicevents () {setlayout (New FlowLayout ());
B1.addactionlistener (New B ());
B1.addactionlistener (New B1 ());
B2.addactionlistener (New B ());
B2.addactionlistener (New B2 ());
Add (B1);
Add (B2); Class B implements ActionListener {public void actionperformed (ActionEvent e) {System.out.println ("A Butto
N was pressed ");
} class Countlistener implements ActionListener {int index;
Public Countlistener (int i) {index = i;}
public void actionperformed (ActionEvent e) {System.out.println ("counted Listener" + index); }
}
Class B1 implements ActionListener {public void actionperformed (ActionEvent e) {System.out.println ("Butto
N 1 pressed ");
ActionListener a = new Countlistener (i++);
V.addelement (a);
B2.addactionlistener (a); } class B2 implements ActionListener {public void actionperformed (ActionEvent e) {System.out.println ("Bu
Tton 2 pressed ");
int end = V.size ()-1;
If (end >= 0) {b2.removeactionlistener (ActionListener) v.elementat (end);
V.removeelementat (end);
}} public static void Main (string[] args) {Frame f = new dynamicevents (); F.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0
);
}
});
F.setsize (300,200);
F.show (); }
} ///:~
The new approach taken in this example includes:
(1) attaching not less than one receiver to each button. Typically, components treat events as multiple styling, which means that we can register many sinks for a single event. When an event is processed as a single shape in a particular assembly, we get Toomanylistenersexception (that is, too many sink exceptions).
(2) During the execution of the program, the receiver is dynamically added and deleted from the button B2. This is done with the method we saw earlier, but each component also has a removexxxlistener () (delete xxx receiver) method to remove various types of sinks.
This flexibility provides more powerful capabilities for our programming.
We note that event receivers are not guaranteed to be invoked when they are added (although in fact most of the execution is done in this way).