Scribble Applet
// this applet allows the user to draw by dragging the mouse
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Scribble11 extends Applet
implements ActionListener, MouseListener, MouseMotionListener
{
private int lastx;
private int lasty;
private Button clearButton;
private Image drawing;
private Graphics drawGraph;
private int width;
private int height;
// add the button for clearing the drawing, get the size of the
// drawing area, and register to listen for mouse events and button
// presses
public void init()
{
clearButton = new Button("Clear");
clearButton.addActionListener(this);
this.add(clearButton);
width = getSize().width;
height = getSize().height;
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
// save the position of the mouse when the user presses the mouse button
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e)
{
lastx = e.getX();
lasty = e.getY();
}
public void mouseReleased(MouseEvent e) { }
// draw a line from the previous position to the current position when the
// user drags the mouse. also save the new position of the mouse
public void mouseDragged(MouseEvent e)
{
drawGraph.drawLine(lastx,lasty,e.getX(),e.getY());
repaint();
lastx = e.getX();
lasty = e.getY();
}
public void mouseMoved(MouseEvent e) { }
// clear the display if the user clicks on the 'clear' button
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Clear"))
clear();
}
public void clear()
{
drawGraph.clearRect(0,0,width,height);
drawGraph.drawRect(0,0,width-1,height-1);
drawGraph.drawRect(1,1,width-3,height-3);
repaint();
}
// override the update method to avoid clearing the applet's display
// area
public void update(Graphics g)
{
paint(g);
}
// initialize the Image for offscreen drawing if necessary, then
// transfer the Image to the applet's display area
public void paint(Graphics g)
{
if (drawing == null)
{
drawing = createImage(width,height);
drawGraph = drawing.getGraphics();
drawGraph.setColor(Color.black);
drawGraph.drawRect(0,0,width-1,height-1);
drawGraph.drawRect(1,1,width-3,height-3);
}
g.drawImage(drawing,0,0,null);
}
}