|
||
|
|
|
|
|
Encapsulating Behavior in Components
The first way to handle events locally to a Component requires that we subclass the Component and override the mouseDown action, or whatever the event of interest is. For example, creating a Button that handles an action is straightforward:
This approach encapsulates the required behavior within the Button object, but requires that we create a new class for each new behavior--a tedious proposition considering how many components a typical GUI has. Further, the behavior of a Component cannot be changed at runtime.
A better solution involves Component observers that allow you to create a single subclass for each Component regardless of the number of different components needed for a GUI. For example, an object that wants to be notified upon a button press could define a ButtonObserver:
Then, a special Button could be defined to notify a ButtonObserver:
This approach has the additional benefit that the event-handling behavior can be changed at runtime by changing the observer field. Here is an applet that employs ButtonObserver and ButtonWithObserver:
Corresponding source code:
The applet itself is considered the button observer and, hence, we pass this to the ButtonWithObserver constructor and implement method pressed in ButtonEventTest. The applet itself is notified when Button b has been pressed. |