[Chapter 7] 7.2 Scribbling in Java 1.0
Author: David Flanagan
Date: Thu Jul 31 15:55:05 1997

#

| Chapter 7 Events |

## 7.2 Scribbling in Java 1.0

Example 7.1 shows a simple applet that uses the Java 1.0 event model. It overrides the `mouseDown()` and `mouseDrag()` methods to allow the user to scribble with the mouse. It overrides the `keyDown()` method and clears the screen when it detects the "C" key. And it overrides the `action()` method to clear the screen when the user clicks on a Clear button. We've seen applets much like this elsewhere in the book; this one is not pictured here.

#### Example 7.1: Scribble: Using the 1.0 Event Model

    import java.applet.*;
    import java.awt.*;
    /** A simple applet using the Java 1.0 event handling model */
    public class Scribble1 extends Applet {
      private int lastx, lasty;    // Remember last mouse coordinates.
      Button clear_button;         // The Clear button.
      Graphics g;                  // A Graphics object for drawing.
      /** Initialize the button and the Graphics object. */
      public void init() {
        clear_button = new Button("Clear");
        this.add(clear_button);
        g = this.getGraphics();
      }
      /** Respond to mouse clicks. */
      public boolean mouseDown(Event e, int x, int y) {
        lastx = x; lasty = y;
        return true;
      }
      /** Respond to mouse drags. */
      public boolean mouseDrag(Event e, int x, int y) {
        g.setColor(Color.black);
        g.drawLine(lastx, lasty, x, y);
        lastx = x; lasty = y;
        return true;
      }
      /** Respond to key presses. */
      public boolean keyDown(Event e, int key) {
        if ((e.id == Event.KEY_PRESS) && (key == 'c')) {
          clear();
          return true;
        }
        else return false;
      }
      /** Respond to Button clicks. */
      public boolean action(Event e, Object arg) {
        if (e.target == clear_button) {
          clear();
          return true;
        }
        else return false;
      }
      /** convenience method to erase the scribble */
      public void clear() {
        g.setColor(this.getBackground());
        g.fillRect(0, 0, bounds().width, bounds().height);
      }
    }

The Java 1.0 Event Model |  | The Java 1.1 Event Model