/* Scribble on a Canvas. * * Functionality: The user can click on the canvas. Lines are drawn to connect the * points where the user clicks . * * Note: all drawing done in the paint() method. * * @author Laura Toma * */ import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class Scribbler1 extends JFrame implements MouseInputListener { //store the crt and previous points where the user clicked on the //screen private Point prevPoint, crtPoint; public Scribbler1() { super("Scribble"); setSize(400, 400); //exit on close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //the points are initially null prevPoint = null; crtPoint = null; setVisible(true); addMouseMotionListener(this); addMouseListener(this); } public void paint(Graphics g) { //draw a line between last two points, if they exist if (prevPoint != null && crtPoint != null) { g.drawLine((int)prevPoint.getX(), (int)prevPoint.getY(), (int)crtPoint.getX(), (int)crtPoint.getY()); } } public void mousePressed(MouseEvent e) { //update last points prevPoint = crtPoint; crtPoint = new Point(e.getX(), e.getY()); //trigger repainting repaint(); } public void mouseDragged(MouseEvent e) { //update last two points prevPoint = crtPoint; crtPoint = new Point(e.getX(), e.getY()); //trigger repainting repaint(); } public void mouseReleased(MouseEvent e) { //update last two points prevPoint = crtPoint = null; } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} public static void main (String args[]) { Scribbler1 s = new Scribbler1(); } };