
// 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 of the panel implements
   MouseMotionListener and MouseListener.
*/


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


public class DoodlePanel extends JPanel
                implements MouseMotionListener, MouseListener
                // could use MouseInputListener
{
  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(this);
    addMouseListener(this);
  } // 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
  }


  // ------------ methods for MouseMotionListener ----------------

  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()
  }  // end of mouseDragged()


  public void mouseMoved(MouseEvent e) {}   // not needed


  // ------------ methods for MouseListener ----------------


  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() + ")" ); 
  }

  public void mouseClicked(MouseEvent e) {}  // not needed 
  public void mouseEntered(MouseEvent e) {}  // not needed 
  public void mouseExited(MouseEvent e) {}   // not needed 

} // end of DoodlePanel class
