Step 3

In step 3, we add function that enables the clear button.

Example Applet


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Step3 extends Applet {

    // Add clear function

    Button clear;
    Panel buttonPanel;
    MyPanel drawPanel;


    public void init() {

        super.init();

        clear = new Button ( "clear" );
        buttonPanel = new Panel ();
        drawPanel = new MyPanel ();

        clear.setBackground ( new Color (187, 00, 00)  );
        clear.setForeground ( Color.white );

        buttonPanel.setBackground ( new Color (00, 102, 155)  );
        buttonPanel.add ( clear );

        drawPanel.setBackground ( Color.white );
        drawPanel.setForeground ( Color.black );

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

        drawPanel.addMouseListener ( drawPanel );
        drawPanel.addMouseMotionListener ( drawPanel );
        clear.addActionListener ( drawPanel );

    }  // end init


}  // end whiteboard
class MyPanel extends Panel implements MouseListener, MouseMotionListener, ActionListener {

    private int last_x, last_y, x, y;
    boolean clicked = false;


   //**********************  Interface Methods
    // MouseListener Methods

    public void mousePressed ( MouseEvent e )  {
        last_x = e.getX();
        last_y = e.getY();
    }  // end mousePressed

    public void mouseReleased ( MouseEvent e )  {
    }  // end mouseReleased

    public void mouseEntered ( MouseEvent e )  {
        requestFocus ();
    }  // end mouseEntered

    public void mouseExited ( MouseEvent e )  {
    }  // end mouseExited

    public void mouseClicked ( MouseEvent e )  {
    }  // end mouseClicked
    // MouseMotionListener Methods

    public void mouseDragged ( MouseEvent e )  {
        Graphics g;
        x = e.getX();
        y = e.getY();
        g = this.getGraphics ();
        g.drawLine ( last_x, last_y, x, y );
        last_x = x;
        last_y = y;
    }  // end mouseDragged
    public void mouseMoved ( MouseEvent e )  {
    }  // end mouseMoved
    // ActionListener Method

    public void actionPerformed ( ActionEvent e )  {
        Graphics g = this.getGraphics ();
        Rectangle r = this.bounds ();
        g.setColor ( this.getBackground () );
        g.fillRect ( 0, 0, r.width, r.height );
        g.setColor ( this.getForeground () );
    }  // end actionPerformed

}  // end MyPanel

Run the applet