import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;

public class demoDraw extends JFrame implements KeyListener, MouseListener{
 GeneralPath gp = new GeneralPath();
 Image buf;
 int MOVETO = 0;
 int LINETO = 1;
 int GRAB  = 2;
 int mode = MOVETO;
 Color fillColor = new Color(0,0,255);
 Vector pts = new Vector();

 public static void main(String [] arg){
		demoDraw d = new demoDraw();
		d.reshape(100,100,500,500);
		d.show();
 }

 public demoDraw(){ 
     //buf = (BufferedImage)this.createImage(500, 500);
	buf =	new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
	addMouseListener(this);
	addKeyListener(this);
    Container c = getContentPane();
    c.setLayout(null);
	demoPalette dp = new demoPalette(this);
	dp.reshape(0,0,55,200);
	c.add(dp);
    setContentPane(c);
    this.requestFocus();
 }
 
 
 public void keyReleased(KeyEvent me){}
 public void keyPressed(KeyEvent me){}
 public void keyTyped(KeyEvent me){
    char key = me.getKeyChar();
	if(key == 'm'){ //MOVETO
	    mode = MOVETO;
		System.out.println("MOVETO mode=="+mode);
	}else if(key == 'l'){ // LINETO
	    mode = LINETO;
		System.out.println("LINETO mode=="+mode);
	}else if(key == 'n'){ //NEW
	    gp = new GeneralPath();
		mode = MOVETO;
		pts = new Vector();
		System.out.println("new gp");
	}
    else if(key == 'd'){  //DRAW
		doFill();
	}
    else if(key == 'g'){  //GRAB
	    mode = GRAB;
	}
 }

 public void doFill(){
	System.out.println("drawing");
    Graphics2D g = (Graphics2D) buf.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0,0,500,500);
    g.setPaint(fillColor);
    g.draw((Shape)gp);
    g.fill((Shape)gp);

    g.setPaint(Color.black);

	for(Enumeration e = pts.elements(); e.hasMoreElements(); ){
		Point p = (Point)e.nextElement();
	    g.fillOval(p.x,p.y,10,10);	
    }
    repaint();
 }


 public void mouseEntered(MouseEvent me){}
 public void mouseExited(MouseEvent me){}
 public void mouseReleased(MouseEvent me){}
 public void mouseClicked(MouseEvent me){}
 public void mousePressed(MouseEvent me){
   int x = me.getX();
   int y = me.getY();
   if(mode==MOVETO){
		 gp.moveTo(x,y);
	  System.out.println(x+" "+y);
		pts.add(new Point(x,y));
   }
   else if(mode==LINETO){
	  System.out.println(x+" "+y);
	  gp.lineTo(x,y);
		pts.add(new Point(x,y));
	  doFill();
   }else{ // GRAB

		for(Enumeration e = pts.elements(); e.hasMoreElements(); ){
			Point p = (Point)e.nextElement();
			System.out.println(p.x+" "+p.y+" close to? "+x+" "+y);
		}
   }

 }

 public void paint(Graphics g){
   g.drawImage(buf,0,0,null);
 }
}
