Event Handling In Java Part II - Explicit-Event Handling (
Page 2 of 6 )
An
alternate way to handle events is to sub class the components and override the
method that receives and dispatches event. For example you can drive a class
from Button class and override the processActionEvent() method. The default
action of the processActionEvent() method is to dispatch the event to the event
listeners.
Example1:
Class OKButton extends Button
{
Public OKButton (String caption)
{
super(caption);
//enable processing of action events
enableEvents(AWTEvent.Action_Event_Mask);
}
Public void processActionEvent(ActionEvent e)
{
// process event, and call superclass method
// as it calls actionPerformed() method
super.processActionEvent(action);
}
}
A subclass can act as an event listener for itself as shown in the
following code:
Class OKButton extends Button implements ActionListener
{
Public OKButton(String caption)
{
super(caption);
//add an action listener to the button
addActionListener(this);
}
Public void actionPerformed(ActionEvent ae)
{
// code to process event
}
}