
// DoodlePanel.java
// Andrew Davison, January 2018, ad@fivedots.coe.psu.ac.th

/* A panel that catches mouse drag events and stores
   the cursor points in the points[] array.
   These are drawn onto the panel at each repaint.

   This version uses anonymous classes that extend
   MouseMotionAdapter and MouseAdapter.
*/


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


public class DoodlePanel extends JPanel
{
  private static final int MAXPOINTS = 5000;

  // for storing the paintable points
  private Point[] points = new Point[MAXPOINTS];
  private int nPoints = 0;


  public DoodlePanel()
  {
    setBackground(Color.white);

    addMouseMotionListener( new MouseMotionAdapter() {
	  public void mouseDragged( MouseEvent e)
      // record the current cursor position, then request a repaint
	  {  if (nPoints < MAXPOINTS)
           points[nPoints++] = new Point(e.getX(), e.getY());
	  // System.out.println( e.getX() + ", " + e.getY() ); 
 		 repaint();   // the repaint will call paintComponent()
	  }
	});

    addMouseListener( new MouseAdapter() {
      public void mousePressed( MouseEvent e)
      { System.out.println( "Mouse pressed at (" + e.getX() + "," +
												   e.getY() + ")" ); 
      }

      public void mouseReleased( MouseEvent e)
      { System.out.println( "Mouse released at (" + e.getX() + "," +
													e.getY() + ")" ); 
      }
    });
  } // end of DoodlePanel() constructor


  public Dimension getPreferredSize()
  // Say how big we would like this panel to be
  {   return new Dimension(500, 300); }


  public void paintComponent(Graphics g)
  // repaint the panel by redrawing all the stored points
  { 
    super.paintComponent(g);   // repaint standard stuff first
    for (int i = 0; i < nPoints; i++)
      g.fillOval( points[i].x, points[i].y, 4, 4);   // the pen is a 4x4 black circle
  }

} // end of DoodlePanel
