// This example is from the book "Java in a Nutshell, Second Edition". // Written by David Flanagan. Copyright (c) 1997 O'Reilly & Associates. // You may distribute this source code for non-commercial purposes only. // You may study, modify, and use this example for any purpose, as long as // this notice is retained. Note that this example is provided "as is", // WITHOUT WARRANTY of any kind either expressed or implied. /* Modified by R. Brown 1/8/99 Instead of giving a name (e.g., MyMouseAdapter) to the adapter class, we use an instance of an unnamed class that implements the MouseListener interface R. Brown 1/6/00: Use anonymous adapter class for MouseMotion events, too */ import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Anonymous extends JApplet { int lastX, lastY; public void init() { // Tell this applet which MouseListener and MouseMotionListener // objects to notify when mouse and mouse motion events occur. /* The following "registration" calls use dynamically allocated instances of a unnamed (anonymous) adapter classes */ this.addMouseListener(new MouseListener () { // A method from the MouseListener interface. Invoked when the // user presses a mouse button. public void mousePressed(MouseEvent e) { lastX = e.getX(); // NOTE: this is Anonymous.lastX, by locality lastY = e.getY(); } // The other, unused methods of the MouseListener interface. public void mouseReleased(MouseEvent e) {;} public void mouseClicked(MouseEvent e) {;} public void mouseEntered(MouseEvent e) {;} public void mouseExited(MouseEvent e) {;} }); this.addMouseMotionListener(new MouseMotionListener () { // A method from the MouseMotionListener interface. Invoked when the // user drags the mouse with a button pressed. public void mouseDragged(MouseEvent e) { Graphics g = getGraphics(); /* NOTE: this is Anonymous.getGraphics(). To write "this.getGraphics() would mean the anonymous adapter's getGraphics(), which doesn't exist... */ int x = e.getX(), y = e.getY(); g.drawLine(lastX, lastY, x, y); lastX = x; lastY = y; } // The other method of the MouseMotionListener interface. (unused) public void mouseMoved(MouseEvent e) {;} }); } }