13.4 Binding events dynamically



One of the benefits of the new AWT event model is flexibility. In the old model you were forced to hard code the behavior of your program, but with the new model you can add and remove event behavior with single method calls. The following example demonstrates this:

Case Study: DynamicEvents.java

The new twists in this example are:

  1. There is more than one listener attached to each Button. Usually, components handle events as multicast, meaning that you can register many listeners for a single event. In the special components in which an event is handled as unicast, you'll get a TooManyListenersException.
  2. During the execution of the program, listeners are dynamically added and removed from the Button b2. Adding is accomplished in the way you've seen before, but each component also has a removeXXXListener( ) method to remove each type of listener. This kind of flexibility provides much greater power in your programming. You should notice that event listeners are not guaranteed to be called in the order they are added (although most implementations do in fact work that way).

Next Page