Step 2

In step 2, we add function that allows the user to draw on the drawing panel by holding down the mouse button and dragging. Note, that no function has been added for the clear button.

Example Applet

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

public class step2 extends Applet{

//  adds drawing capability to drawPanel

Button button = new Button ("Clear");
Panel buttonPanel = new Panel ( );
MyPanel2 drawPanel = new MyPanel2 ();

  public void init ( ){

    drawPanel.setBackground (Color.white);
    button.setBackground (Color.green);
    button.setFont ( new Font ("Helvetica", Font.BOLD, 18) );

    buttonPanel.add (button);

    setLayout (new BorderLayout ( ) );
    add ("North", buttonPanel);
    add ("Center", drawPanel);

  } // end init

}// end step2

class MyPanel2 extends Panel {

int last_x = 0;
int last_y = 0;
int x = 0;
int y = 0;

  public boolean mouseDown ( Event event, int x, int y ) {

    last_x = x;
    last_y = y;

    return true;

  }  // end mouseDown

  public boolean mouseDrag ( Event event, int x, int y ) {

    Graphics g = getGraphics ( );
    g.drawLine ( last_x, last_y, x, y );

    last_x = x;
    last_y = y;

    return true;

  }  // end mosueDrag

} // end MyPanel2

Run the applet