<< Chapter < Page | Chapter >> Page > |
The source-listener event model that I will illustrate later doesn't suffer from that restriction.
Listing 5 shows the beginning of an anonymous class to perform low-level event handling similar tothat shown in Listing 4 .
This code defines an anonymous inner class that implicitly extends Button and has mouse events enabled. I provided this class primarily for comparison with the local class named BaldButton . This class is an anonymous alternative to the local BaldButton class.
An argument to the add method
Note that the definition of this anonymous class appears as an argument to the add method for the frame. Thus, the anonymous object instantiated from the anonymous class is added as thesecond (middle) button in Figure 2 .
Extends the Button class
Note also that this form of anonymous class implicitly extends the Button class. Once again, this makes it possible to override the processMouseEvent method belonging to the Button class.
An instance initializer
As I mentioned earlier in this module, it is not possible to define a constructor for an anonymous class. However, it is possible to define aninstance initializer.
(In Listing 5 , the instance initializer consists of two statements enclosed by matching curly brackets.)
This class defines an instance initializer that
The screen output
Therefore, the instantiation of this anonymous object causes the text shown in Figure 6 to appear on the screen. About all you can tell by looking at this class name is that it is the name of a file thatrepresents an anonymous class.
Overridden processMouseEvent method
The remaining code in the anonymous class definition is shown in Listing 6 . The code in Listing 6 consists of
Same code as before
The code in this overridden processMouseEvent method is essentially the same as that shown for the local class in Listing 4 , except that it produces a different message on the screen when the user clicks the button.
Clicking the middle button in Figure 2 produces the screen output shown by the sixth line in Figure 4 .
Implementing a listener interface
Now I'm going to switch from low-level event handling to source-listener event handling. The code to accomplish this begins in Listing 7 .
With this event handling model:
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?