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

public class Lines2D
 {
	public static void main(String[] args)
   {
      LinesFrame frame = new LinesFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.show();
   }
}

/**
   A frame containing a panel for drawing polygonals
*/
class LinesFrame extends JFrame
{
   public LinesFrame()
   {
      setTitle("Drawing lines");
      setSize(WIDTH, HEIGHT);

      // add panel to frame

      LinesPanel panel = new LinesPanel();
      Container contentPane = getContentPane();
      contentPane.add(panel);
   }

   public static final int WIDTH  = 300;
   public static final int HEIGHT = 200;  
}

/**
   A panel with mouse operations for adding and removing squares.
*/
class LinesPanel extends JPanel
{
   public LinesPanel()
    {					
      starts= new ArrayList();	// starting points of lines
      ends= new ArrayList();      // ending points of lines
     
      Point pivot;                          // start of current line
      Point currentPoint;                   // current end of line
    
      addMouseListener(new MouseHandler());
      addMouseMotionListener(new MouseMotionHandler());
    }

    void addline(Point endpoint) 
    {
        starts.add(pivot);
        ends.add(endpoint);
        currentPoint = null;
        pivot = null;
        repaint();
    }

    public void paintComponent(Graphics g)
    {
      super.paintComponent(g);
      //Graphics2D g2 = (Graphics2D)g;

        // Draw existing lines
        for (int i = 0; i < starts.size(); i++) {
            g.drawLine(((Point)starts.get(i)).x,((Point)starts.get(i)).y,
			((Point)ends.get(i)).x,((Point)ends.get(i)).y);
        }

        // draw current line
        g.setColor(Color.blue);
        if (currentPoint != null)
            g.drawLine(((Point)pivot).x,((Point)pivot).y,
			((Point)currentPoint).x,((Point)currentPoint).y);
    }

    private class MouseHandler extends MouseAdapter
    {
	    public void mousePressed(MouseEvent evt) 
	    {
	        Point pivot = evt.getPoint();
	    }
	       
	
	    public void mouseReleased(MouseEvent evt) 
	    {
	        addline(evt.getPoint());
	    }   
    }
    private class MouseMotionHandler implements MouseMotionListener
    {
	    public void mouseDragged(MouseEvent evt) 
	    {
	        Point currentPoint = evt.getPoint();
	        repaint();
	    }
		public void mouseMoved(MouseEvent evt)
		{
		}
    }
	
	private ArrayList starts;
	private ArrayList ends;
	private Point2D pivot;                         // start of current line
	private Point2D currentPoint;                  // current end of line
}
