Java Reference
In-Depth Information
Window Listeners
Window listeners can be added to a window (and many of the Window subclasses like Frame ). A window listener is
on the alert for a user clicking the close window button and six other actions. For each of these possible “events” the
programmer must code a unique method to handle the event. Just as the main method's header must be coded in a
very specific way (name, number, and type of parameters, return value, etc.), these method headers have a specific
syntax that must be followed. Another requirement is that all seven methods must be coded; if not, the JVM will return
an error.
Think of the requirement in terms of the sentry example: you must tell the sentry what to do when all the possible
events (in this case, seven) occur.
The following four steps must be performed to create a WindowListener:
Import the WindowListener and WindowEvent classes
1.
2.
Implement the WindowListener
3.
Code the seven required methods
4.
Add the window listener to the frame
A window listener can be created as separate class, however, a Frame subclass can also be defined as a window
listener (i.e., it can “implement the window listener interface”). Putting the code to do this into every Frame subclass
we create (like EmpFrame) would be very inefficient. Instead we will create a new class called UsefulFrame to hold
all the “window listener code” and then make EmpFrame (and all our future frames) subclasses of UsefulFrame.
In this way, all our frames inherit the window listener functionality. Sound like a good idea? I hope you said yes,
because that's what we are going to do.
Tutorial: Creating a Superclass
Have you noticed that a superclass is simply a class like any other class? It's the extends statement (in the subclass
header) that actually identifies a class as a superclass. To say it another way, it's the extends statement that establishes
the superclass/subclass relationship.
Let's see an example:
1.
In RAD, create a new package called c4 in the Tutorials project.
2.
Copy the three Employee classes from c3 into c4.
3.
In the Navigation Tree, click on c4.
On the Menu bar, click File , New , and then Class .
4.
5.
At the “New Java Class” window:
Specify the class name as UsefulFrame.
Specify the superclass as java.awt.Frame.
Do not have any other methods or stubs generated.
6.
Click the Add button to begin implementing a window listener.
The “Implemented Interfaces Selection” window will be displayed. Because listeners control what happens when
the user interacts with the program, the listeners are referred to as “interfaces.” Instead of explicitly creating a listener
object and then adding it to the GUI component (like a frame), a listener interface can be “implemented” by the GUI
component class (i.e., EmpFrame). When the GUI component (EmpFrame) object is created, it is also considered a
listener object. Oddly, though, you still have to add the GUI component to itself.
 
Search WWH ::




Custom Search