Scribble.java Source code

Java tutorial

Introduction

Here is the source code for Scribble.java

Source

/*
 * This example is from the book "Java Foundation Classes in a Nutshell".
 * Written by David Flanagan. Copyright (c) 1999 by 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.
 */

import java.applet.*;
import java.awt.*;

/** A simple applet using the Java 1.0 event handling model */
public class Scribble extends Applet {
    private int lastx, lasty; // Remember last mouse coordinates.
    Button erase_button; // The Erase button.
    Graphics g; // A Graphics object for drawing.

    /** Initialize the button and the Graphics object */
    public void init() {
        erase_button = new Button("Erase");
        this.add(erase_button);
        g = this.getGraphics();
        this.requestFocus(); // Ask for keyboard focus so we get key events
    }

    /** Respond to mouse clicks */
    public boolean mouseDown(Event e, int x, int y) {
        lastx = x;
        lasty = y; // Remember where the click was
        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); // Draw from last position to here
        lastx = x;
        lasty = y; // And remember new last position
        return true;
    }

    /** Respond to key presses: Erase drawing when user types 'e' */
    public boolean keyDown(Event e, int key) {
        if ((e.id == Event.KEY_PRESS) && (key == 'e')) {
            g.setColor(this.getBackground());
            g.fillRect(0, 0, bounds().width, bounds().height);
            return true;
        } else
            return false;
    }

    /** Respond to Button clicks: erase drawing when user clicks button */
    public boolean action(Event e, Object arg) {
        if (e.target == erase_button) {
            g.setColor(this.getBackground());
            g.fillRect(0, 0, bounds().width, bounds().height);
            return true;
        } else
            return false;
    }
}