top-level classes in this program. MousePressedDemo extends Applet, and MyMouseAdapter
extends MouseAdapter. The init( ) method of MousePressedDemo instantiates
MyMouseAdapter and provides this object as an argument to the addMouseListener( )
method.
Notice that a reference to the applet is supplied as an argument to the MyMouseAdapter
constructor. This reference is stored in an instance variable for later use by the mousePressed( )
method. When the mouse is pressed, it invokes the showStatus( ) method of the applet
through the stored applet reference. In other words, showStatus( ) is invoked relative to
the applet reference stored by MyMouseAdapter.
// This applet does NOT use an inner class.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MousePressedDemo" width=200 height=100>
</applet>
*/
public class MousePressedDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
MousePressedDemo mousePressedDemo;
public MyMouseAdapter(MousePressedDemo mousePressedDemo) {
this.mousePressedDemo = mousePressedDemo;
}
public void mousePressed(MouseEvent me) {
mousePressedDemo.showStatus("Mouse Pressed.");
}
}
The following listing shows how the preceding program can be improved by using an
inner class. Here, InnerClassDemo is a top-level class that extends Applet. MyMouseAdapter
is an inner class that extends MouseAdapter. Because MyMouseAdapter is defined within
the scope of InnerClassDemo, it has access to all of the variables and methods within the
scope of that class. Therefore, the mousePressed( ) method can call the showStatus( ) method
directly. It no longer needs to do this via a stored reference to the applet. Thus, it is no longer
necessary to pass MyMouseAdapter( ) a reference to the invoking object.
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home