Step 3

In step 3, we add function that enables the clear button. Note, that we are not yet able to type text into the drawing panel.

Example Applet

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

public class step3 extends Applet{

// handles button events and adds clear function

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

  public boolean action (Event event, Object arg) {

    if (event.target == button )  {
      return drawPanel.clear ( );
    }  // end if
    else return false;

  }  // end action

}// end step3

class MyPanel3 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

  public boolean clear ( )  {

    Graphics g = getGraphics ( );

    Rectangle r = this.bounds ( );
    g.setColor ( this.getBackground ( ) );
    g.fillRect ( 0, 0,  r.width, r.height );
    g.setColor ( this.getForeground ( ) );

    return true;

  }  // end clear

} // end MyPanel3

Run the applet