start page | rating of books | rating of authors | reviews | copyrights

Java in a Nutshell

Previous Chapter 7
Events
Next
 

7.4 Scribbling in Java 1.1

The Java 1.1 event model is quite flexible, and, as we'll see, there are several different ways you can use it to structure your event-handling code. Example 7.2 shows the first technique. Once again, this is our basic Scribble applet, this time using the Java 1.1 event model. This version of the applet implements the MouseListener and MouseMotionListener interfaces itself, and registers itself with its own addMouseListener() and addMouseMotionListener() methods.

Example 7.2: Scribble: Implementing the Listener Interfaces Directly

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Scribble2 extends Applet
                      implements MouseListener,  MouseMotionListener {
  private int last_x, last_y;
  public void init() {
    // Tell this applet what MouseListener and MouseMotionListener
    // objects to notify when mouse and mouse motion events occur.
    // Since we implement the interfaces ourself, our own methods are called.
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
  }
  // A method from the MouseListener interface.  Invoked when the
  // user presses a mouse button.
  public void mousePressed(MouseEvent e) {
    last_x = e.getX();
    last_y = e.getY();
  }
  // A method from the MouseMotionListener interface.  Invoked when the
  // user drags the mouse with a button pressed.
  public void mouseDragged(MouseEvent e) {
    Graphics g = this.getGraphics();
    int x = e.getX(), y = e.getY();
    g.drawLine(last_x, last_y, x, y);
    last_x = x; last_y = y;
  }
  // 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) {;}
  // The other method of the MouseMotionListener interface.
  public void mouseMoved(MouseEvent e) {;}
}


Previous Home Next
The Java 1.1 Event Model Book Index Scribbling with Inner Classes

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java