Java Reference
In-Depth Information
7.
At the “Implemented Interfaces Selection” window, start typing Window.
RAD will display a list of matching interface names.
Click on
WindowListener
in the list and then the OK button.
8.
In the “New Java Class” window, java.awt.event.WindowListener will be displayed in the Interfaces pane.
9.
On the “New Java Class” window, click the Finish button.
The source code will be redisplayed and the executable code should look like the following:
package
c4;
import
java.awt.Frame;
import
java.awt.event.WindowListener;
public class
UsefulFrame
extends
Frame
implements
WindowListener {
}
So far, RAD has done part of step 1 and all of step 2 (of the four steps needed to enable the window listener).
However, an error message is generated because step 3 has not been done. Just as we must tell the sentry what to
do before he can go on guard duty, we must tell the WindowListener what to do by coding the seven methods. Each
method that is not coded results in a syntax error message saying that the method must be implemented.
10.
Insert the following code before the closing brace in the class's body:
public void
windowClosing(WindowEvent e) {
this
.dispose();
}
public void
windowClosed(WindowEvent e) {}
public void
windowDeiconified(WindowEvent e) {}
public void
windowIconified(WindowEvent e) {}
public void
windowOpened(WindowEvent e) {}
public void
windowActivated(WindowEvent e) {}
public void
windowDeactivated(WindowEvent e) {}
Ouch, now there is an error on every line. Can you figure out the problem and solution?
As mentioned, the seven methods must be included in the class for the window listener to work. However, that
doesn't mean they have to do anything. As a matter of fact, only the first method, windowClosing, does anything. To
use our analogy (for the last time, I promise), we are telling the sentry/window listener to do nothing for the other six
events. However, when someone clicks the close button, the frame's dispose method will be executed. The dispose
method destroys (i.e., removes from main memory) the frame and all its components.
Did you figure out the cause of the error messages? Notice that the window listener passes a
WindowEvent
object
to the seven methods. (Event objects contain information that can be very useful. We will use event information
later when we implement multiple buttons.) The problem is that the JVM can't find the
WindowEvent
class. We must
include an import statement for the
WindowEvent
.
11.
Add the following after the existing import statements (you may have to expand the code
to see both import statements):
import
java.awt.event.WindowEvent;