import java.awt.*;
import java.awt.event.*;

public class DrawingCanvas extends Canvas implements MouseListener,
                MouseMotionListener {
    public DrawingCanvas(){
        addMouseListener(this);
    }

    public void clear(){
        Graphics g = getGraphics();
        update(g);
    }

    // The MouseListener methods.
    public void mousePressed(MouseEvent e){
        // Pick up the point and remember it.
        setLastPoint(e.getPoint());
        setDrawing(true);
    }

    public void mouseReleased(MouseEvent e){
        if(getDrawing()){
            drawToPoint(e.getPoint());
            setDrawing(false);
        }
    }

    public void mouseClicked(MouseEvent e){
        // Draw a dot.
        Graphics g = getGraphics();
        int x = e.getX();
        int y = e.getY();
        g.drawLine(x,y,x,y);
    }

    public void mouseEntered(MouseEvent e){
        // Not interested in this event.
    }

    public void mouseExited(MouseEvent e){
        // Cancel any drawing.
        setDrawing(false);
    }

    // The MouseMotionListener methods
    public void mouseDragged(MouseEvent e){
        drawToPoint(e.getPoint());
    }

    public void mouseMoved(MouseEvent e){
        drawToPoint(e.getPoint());
    }

        // Draw from lastPoint to p2 and make p2 the new lastPoint.
    protected void drawToPoint(Point p2){
        Graphics g = getGraphics();
        Point p1 = getLastPoint();
        g.drawLine(p1.x,p1.y,p2.x,p2.y);
        setLastPoint(p2);
    }

    protected boolean getDrawing(){
        return drawing;
    }

    protected void setDrawing(boolean d){
        // Make sure this represents a change of state.
        if(d != drawing){
            if(d){
                addMouseMotionListener(this);
            }
            else{
                removeMouseMotionListener(this);
            }
            drawing = d;
        }
    }

    protected Point getLastPoint(){
        return lastPoint;
    }

    protected void setLastPoint(Point p){
        lastPoint = p;
    }

    // Are we drawing at the moment?
    private boolean drawing = false;
    // Where we last drew to.
    Point lastPoint;
}
