How to Implement an Event Handler

The Component class defines many event-handling methods, and you can override any of them. Except for one all-purpose method (handleEvent()), each event-handling method can be used for only one particular type of event. We recommend that you avoid the all-purpose method, if possible, and instead override the event-handling method that's specific to the type of event you need to handle. This approach tends to have fewer unintended side effects.

When an event occurs, the event-handling method that matches the event type is called. Specifically, the Event is first passed to the handleEvent() method, which (in the default implementation of handleEvent()) calls the appropriate method for the event type.

All the event-handling methods have at least one argument (the Event) and return a boolean value. The return value indicates whether the method completely handled the event. By returning false, the event handler indicates that the event should continue to be passed up the component hierarchy. By returning true, the event handler indicates that the event should not be forwarded any further. The handleEvent() method should almost always return super.handleEvent(), to ensure that all events are forwarded to the appropriate event-handling method.

Important: Like drawing methods, all event handler methods must execute quickly! Otherwise, they'll destroy the perceived performance of your program. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread (or sending a request to another thread) to perform the operation. For help on using threads, see Threads of Control(in the Writing Java Programs trail).

The Keyboard Focus

Many components -- even those primarily operated with the mouse, such as buttons -- can be operated by the keyboard. For a key press to affect a component, the component must have the keyboard focus.

At any given time, at most one window and one component in that window can have the keyboard focus. How windows get the keyboard focus is system dependent. But once a window has the focus, you can use the Component requestFocus() method to request that a component get the focus.

When a component gets the focus, its gotFocus() method is called. When a component loses the focus, its lostFocus() method is called.


Gdańsk 03.05.1998