/* * ====================================================================== * File : SimpleDraw.java -- This applet let you draw with the mouse. * * Written By : David Chancogne September 1997 * ====================================================================== */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class SimpleDraw extends Applet { int last_x; // Last position of the mouse. int last_y; // Last position of the mouse. private Button clearButton; // This is the "Clear" Button. public void init() { // Set the background color. this.setBackground(Color.white); // Create and add 'Clear' button to applet. clearButton = new Button("Clear"); this.add(clearButton); // Add the 3 mouse listeners. clearButton.addMouseListener(new ClearButtonListener(this)); this.addMouseListener(new MousePressedListener(this)); this.addMouseMotionListener(new MouseDraggedListener(this)); } // End of method init } // End of class SimpleDraw class MousePressedListener extends MouseAdapter { SimpleDraw applet; // The calling applet public MousePressedListener(SimpleDraw a) { applet= a; } public void mousePressed(MouseEvent e) { applet.last_x = e.getX(); applet.last_y = e.getY(); } // End of method mousePressed } // End of class MousePressedListener class MouseDraggedListener extends MouseMotionAdapter { SimpleDraw applet; // The calling applet. public MouseDraggedListener(SimpleDraw a) { applet =a; } public void mouseDragged(MouseEvent e) { // Call the applet drawing method. Graphics g = applet.getGraphics(); g.drawLine(applet.last_x, applet.last_y, e.getX(), e.getY()); applet.last_x = e.getX(); applet.last_y = e.getY(); } // End of method mouseDragged } // End of class MouseDraggedListener class ClearButtonListener extends MouseAdapter { SimpleDraw applet; // The calling applet. public ClearButtonListener(SimpleDraw a) { applet = a; } // End of constructor method public void mouseReleased(MouseEvent e) { // Get the graphic context Graphics g = applet.getGraphics(); // Draw a rectangle with the same color as the background g.setColor(applet.getBackground()); Dimension r = applet.getSize(); g.fillRect(0, 0, r.width, r.height); } // End of method mouseReleased } // End of class ClearButtonListener