Inner Classes As Event Handlers

BillKayser

KyleBrown pointed out in BeansNotObserverObservable that a shortcoming of the AWT eventing is that the interface for event listeners is fixed, as opposed to the model in SelfAddressedStampedEnvelope where you can specify the message you want to receive for a particular event.

The problem occurs when a particular class needs to listen for the same event on several different objects, like Lists in a panel. You have to check the source or command argument to see which object generated the event.

A small point, but one technique I find useful is employing anonymous inner classes as handlers and assigning them as listeners to the sources. It avoids the conditionals of multiplexing events through one method.

Here's a fragment of code which shows how it looks.

    public Test()
    {
okButton.addActionListener(okPressHandler);
cancelButton.addActionListener(cancelPressHandler);
    }

ActionListener okPressHandler = new ActionListener() { public void actionPerformed(ActionEvent e) { status = OK; } }; ActionListener cancelPressHandler = new ActionListener() { public void actionPerformed(ActionEvent e) { status = CANCEL; } };


Agreed. Inner classes are a nice way around the limitations of Event handlers, if your environment supports them, which sadly, VisualAge for Java doesn't :(

As an aside, I was surprised to find in the book JavaInANutshell, 2nd edition, an implementation of SelfAddressedStampedEnvelope for Event handlers in their section on reflection in Java.

KyleBrown


CategoryJava


EditText of this page (last edited December 28, 2000) or FindPage with title or text search