Lesson 8 | Using event adapters |
Objective | Learn how to use event adapters. |
Using Event Adapters - JavaBeans
Since event adapters are classes and not interfaces, they are a little tricky to use; you can't just implement them in an application class. To use an adapter class, you have to create an inner class, within the application class, that derives from the adapter class. You then implement only the event response methods you need in the inner class. Following is an example of such an inner class called MouseHandler
:
class MyApp extends Frame {
...
class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
}
...
}
The MouseHandler
inner class, which is located within the application class definition, extends the MouseAdapter
class and implements only one method, mouseClicked()
. With this approach you still have to register the application as an event listener, but this time the listener is specified as an instance of the adapter derived inner class instead of the application object itself:
someBean.addMouseListener(new MouseHandler());
Incidentally, this code is located in the application class's constructor, which is usually the most convenient place to register event listeners.
Event Adapters - Exercise
Click the Exercise link below to use an event adapter to handle mouse motion events.
Event Adapters - Exercise
In the next lesson, you learn how events are delivered.