<applet code="AdapterDemo" width=300 height=100>
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
As you can see by looking at the program, not having to implement all of the methods
defined by the MouseMotionListener and MouseListener interfaces saves you a considerable
amount of effort and prevents your code from becoming cluttered with empty methods. As
an exercise, you might want to try rewriting one of the keyboard input examples shown
earlier so that it uses a KeyAdapter.
Inner Classes
In Chapter 7, the basics of inner classes were explained. Here you will see why they are
important. Recall that an inner class is a class defined within another class, or even within an
expression. This section illustrates how inner classes can be used to simplify the code when
using event adapter classes.
To understand the benefit provided by inner classes, consider the applet shown in the
following listing. It does not use an inner class. Its goal is to display the string "Mouse Pressed"
in the status bar of the applet viewer or browser when the mouse is pressed. There are two
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks