
// 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 inner 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 MouseMotionHandler() );
    addMouseListener( new MouseHandler() );
  } // 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
  }


  // ---------------------- inner classes --------------------------


  class MouseHandler extends 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 MouseHandler class


  class MouseMotionHandler extends MouseMotionAdapter 
  {
    public void mouseDragged( MouseEvent e)
     {
       if (nPoints < MAXPOINTS)
         points[nPoints++] = new Point(e.getX(), e.getY());
       repaint(); 
     }
  }   // end of MouseMotionHandler class


} // end of DoodlePanel
