The Java Program: Basic.java

  1 // Basic.java -- Handling mouse events in JDK 1.0; from Anuff, page 224
  2 
  3 /*
  4      <applet code=Basic width=350 height=250></applet>
  5 */
  6 
  7 import java.util.Date;
  8 import java.applet.Applet;
  9 import java.awt.*;
 10 
 11 public class Basic extends Applet {
 12    Date startDate = null;
 13    Date mouseDownDate = null;
 14    Date mouseDragDate = null;
 15    Date mouseUpDate = null;
 16    int down_x = 0, down_y = 0;
 17    int drag_x = 0, drag_y = 0;
 18    int up_x   = 0,   up_y = 0;
 19 
 20    public void start () {
 21       startDate = new Date();
 22       repaint();
 23    }
 24 
 25    static String getTime (Date d) {
 26       int m = d.getMinutes(), s = d.getSeconds();
 27       return (m+":"+(s>9?"":"0")+s);
 28    }
 29 
 30    public void paint (Graphics g) {
 31       g.drawRect (0, 0, size().width-1, size().height -1);
 32 
 33       if (startDate != null) {
 34          g.drawString ("Started at " + startDate.toString(), 10, 40);
 35       }
 36 
 37       if (mouseDownDate != null) {
 38          g.drawString ("Mouse down at: "+getTime(mouseDownDate),10,60);
 39          g.drawString ("X: " + down_x + " Y: " + down_y, 10, 80);
 40          g.drawOval (down_x-5, down_y-5, 10, 10);
 41       }
 42 
 43       if (mouseDragDate != null) {
 44          g.drawString ("Mouse drag at: "+getTime(mouseDragDate),10,100);
 45          g.drawString ("X: " + drag_x + " Y: " + drag_y, 10, 120);
 46          g.drawLine (down_x, down_y, drag_x, drag_y);
 47          g.fillRect (drag_x-3, drag_y-3, 6, 6);
 48       }
 49 
 50       if (mouseUpDate != null) {
 51          g.drawString ("Mouse up at:   "+getTime(mouseUpDate),10,140);
 52          g.drawString ("X: " + up_x + " Y: " + up_y, 10, 160);  
 53       }
 54    }
 55 
 56    public boolean mouseDown (Event evt, int x, int y) {
 57       mouseDownDate = new Date();
 58       mouseDragDate = null;
 59       mouseUpDate   = null;
 60       down_x = x;  down_y = y;
 61       repaint ();
 62       return true;
 63    }
 64 
 65    public boolean mouseDrag (Event evt, int x, int y) {
 66       mouseDragDate = new Date();
 67       drag_x = x;  drag_y = y;
 68       repaint ();
 69       return true;
 70    }
 71     
 72    public boolean mouseUp (Event evt, int x, int y) {
 73       mouseUpDate = new Date();
 74       up_x = x;  up_y = y;
 75       repaint ();
 76       return true;
 77    }
 78 }