// Lines.java
// Demos mouseDragged, mousePressed and mouseReleased events
// APPLET CODE="Lines.class" HEIGHT=250 WIDTH=250
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Lines extends JApplet {
	final int MAXLINES = 10;
	Point starts[ ];  // starting points
	Point ends[ ];  // ending points
	Point anchor;  // start of current line
	Point currentPoint;  // end of current line
	int currLine = 0;  // number of lines

	public void init( ) {
		starts = new Point[ MAXLINES ];
		ends = new Point[ MAXLINES ];
		setBackground( Color.white );

		addMouseMotionListener(
			new MouseMotionAdapter( ) {
				public void mouseDragged( MouseEvent e ) {
					if ( currLine < MAXLINES ) {
						currentPoint = new Point( e.getX( ), e.getY( ) );
						repaint( );
					}
				}
			}
		);

		addMouseListener(
			new MouseAdapter( ) {
				public void mousePressed( MouseEvent e ) {
					if ( currLine < MAXLINES )
						anchor = new Point( e.getX( ), e.getY( ) );
					else
						showStatus( "Too many lines." );
				}

				public void mouseReleased( MouseEvent e ) {
					if ( currLine < MAXLINES )
						addLine( e.getX( ), e.getY( ) );
				}
			}
		);
	}

	// helper or utility method
	void addLine( int x, int y ) {
		starts[ currLine ] = anchor;
		ends[ currLine ] = new Point( x, y );   // ends[ currLine ] = currentPoint; 

		currLine++;
		currentPoint = null;
		anchor = null;
		repaint( );
	}

	public void paint( Graphics g ) {
		// erase screen each time repaint is called
		g.setColor( Color.white );
		g.fillRect( 0, 0, 250, 250 );

		// Draw existing lines
		g.setColor( Color.blue );
		for ( int i = 0; i < currLine; i++ ) {
			g.drawLine( starts[ i ].x, starts[ i ].y, ends[ i ].x, ends[ i ].y);
		}
	
		// draw current line
		g.setColor( Color.red );
		if ( currentPoint != null )
			g.drawLine( anchor.x, anchor.y, currentPoint.x, currentPoint.y );
	}
}