• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating an Event Listener  RSS feed

Khamon Mann
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following is a cookbook for Event Listener creation. It has helped me in various mock tests. Tell me what you think.
1. If coding the Listener as an anonymous class, skip ahead to step 4.
2. Instantiate a named class, which could be a stand-alone class or an inner class. This will create <classInst>, which is needed in step 5.
3. <ClassType> <classInst> = new <ClassType> ( );
4. Code the call to the inherited addXyListener method.
5. <AWTComponentInst>.addXyListener( <classInst> );
6. Step 5�s <AWTComponentInst> could be an instantiation of like a button, list, choice, textArea, etc.
7. If ref�ing the top-level container, step 5�s <AWTComponentInst> could be an instantiation of a frame, the keyword "this", or blank.
8. Step 5�s addXyListener is addActionListener, addWindowListener, or any of the other valid addXyListener methods.
9. If step 5�s <classInst> is from step 2, skip ahead to building the named class. Skip to step 14.
10. Substitute an anonymous class for step 5�s <classInst>, with the entire anonClass coded inside of step 5�s parens.
11. ( new Xy[Listener|Adapter] ( ) { methOverride { methBody } } );
12. Step 5�s parens and semi-colon were repeated in step 11, for continuity. Seems odd that step 11 ends with 2 closing braces, a closing paren, and semi-colon, however that�s correct syntax, for sure. Step 11�s new object can be either a Listener or an Adapter.
13. Step 11�s { methOverride { methBody } } is common to the named class implementation. Skip to step 17.
14. Declare the named class. This could be a stand-alone class or an inner class. Remember the "extends" for the adapter (if any) and/or the "implements" for the Listeners (if any).
15. �class <ClassType> extends XyAdapter implements XyListener{ methOverride { methBody } }
16. Step 15 would, for sure, have an extends and/or an implements clause. Could be 0, 1, or more Listeners.
17. Back to commonality. Override the method(s) you�re interested in. If it�s an anonymous class, there�s probably only one overridden method in the class. Examples below:
18. public void actionPerformed( ActionEvent evt ) { do something }
19. public void windowClosing( WindowEvent evt ) { System.exit(0); }
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!