source file name: freehand1.java

import java.awt.*; 

import javax.swing.*; 

import java.awt.event.*; 

public class freehand1 extends JFrame implements MouseListener, MouseMotionListener, KeyListener ,ActionListener

 { 

int lx,ly;

 Color col=Color.pink; 

 public static void main(String as[]) 

{

freehand1 f=new freehand1();

f.setTitle("Freehand Drawing Program");

f.setSize(300,400);

f.setVisible(true);

}

public freehand1()

{

setLayout(null);

Button bt=new Button("colors");

bt.setBounds(100,100,50,30);

add(bt);

bt.addActionListener(this);

addKeyListener(this);

addMouseListener(this);

addMouseMotionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

col=Color.green;

int r=(int)(255*Math.random());

int g=(int)(255*Math.random());

int b=(int)(255*Math.random());

col=new Color(r,g,b);

//repaint();

}

public void keyReleased(KeyEvent ke) {}

public void keyTyped(KeyEvent ke) {}

public void keyPressed(KeyEvent ke)

 {

char ch=ke.getKeyChar();

if(ch=='c')

repaint();

}

public void mouseExited(MouseEvent me)

{}

public void mouseEntered(MouseEvent me)

{}

public void mousePressed(MouseEvent me)

{

int x=me.getX();

int y=me.getY();

lineto(x,y);

requestFocus();// transfer control to keyboard

}


public void mouseReleased(MouseEvent me)

{}

public void mouseClicked(MouseEvent me)

{}

public void mouseMoved(MouseEvent me)

{}

public void mouseDragged(MouseEvent me)

{

int x=me.getX();

int y=me.getY();

moveto(x,y);

}

public void lineto(int x, int y)

{

lx=x;

ly=y;

}

public void moveto(int x, int y)

{

Graphics g=getGraphics();

g.setColor(col);

g.drawLine(lx,ly,x,y);

lineto(x,y);

}

}

output: