import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * A window that allows you to draw free hand
 * Left  click mouse and drag to draw
 * Right click mouse to clear 
 */

public class xDraw extends JFrame 
           implements MouseListener, MouseMotionListener  
{
    Point startPt;              //Point class available in awt 
    Point endPt;                //has x and y coordinate            

    public static void main(String[] arguments) {

        xDraw tablet = new xDraw();
    }

    public xDraw ()                //constructor
    {
        setTitle("Let's Draw");                     //set title       
        setDefaultCloseOperation(EXIT_ON_CLOSE);    //action when click on X
        setSize(500, 300);

        Container panel = getContentPane();     //get reference to the content pane

        panel.setBackground(Color.white);

        setVisible(true);                       //make window visible

        addMouseListener(this);                 //add event handler for mouse click
        addMouseMotionListener(this);           //add event handler for mouse move
    }

    public void mousePressed(MouseEvent evt)         
    {
        int X = evt.getX();                     //get mouse x coordinate
        int Y = evt.getY();                     //get mouse y coordinate
        startPt = new Point(X, Y);              //create a start Point
    }
    
    public void mouseDragged(MouseEvent evt)        //will be called repeatedly 
    {
        endPt = new Point(evt.getX(), evt.getY());  //create an end Point

        Graphics g = getGraphics();                 //get a ref to graphics obj
                                                    //access screen device      

        g.drawLine(startPt.x, startPt.y, endPt.x, endPt.y);  //draw from start to end

        setTitle(endPt.toString());                 //display x,y in title bar
                            
        startPt = endPt;                            //new starting point
    }

    public void mouseClicked(MouseEvent evt)         
    {
        int button = evt.getModifiers();            //which button pressed?

        if (button == MouseEvent.BUTTON1_MASK)      //right button. value=16 
            mouseDragged(evt);                      //call mouseDragged
                                                    //to paint a dot

        if (button == MouseEvent.BUTTON3_MASK)      //left button. value=4 
        {
            repaint();                              //repaint - i.e. clear
            setTitle("Cleared");
        }
    }
    
    public void mouseReleased(MouseEvent evt) { }       //must implement
    public void mouseEntered(MouseEvent evt)  { }       //even if empty
    public void mouseExited(MouseEvent evt)   { }       
    public void mouseMoved(MouseEvent evt)    { }
    
}