/* * Scribble on a Canvas. * * Functionality: The user can click on the canvas. Lines are drawn to connect the * points where the user clicks . * * Note: the drawing is not in paint() * * @author Laura Toma, csci 210 * */ import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class Scribbler2 extends JFrame implements MouseInputListener { //stores the last point where the user clicked private Point prevPoint; public Scribbler2() { super("Scribble"); setSize(400, 400); //exit on close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); addMouseMotionListener(this); addMouseListener(this); } //when the mouse is pressed, record the position public void mousePressed(MouseEvent e) { System.out.println("mouse pressed"); prevPoint = new Point(e.getX(), e.getY()); } //when the mouse is dragged, connect it to the previous point and //record the new position public void mouseDragged(MouseEvent e) { System.out.println("mouse dragging"); Graphics g = this.getGraphics(); g.drawLine((int)prevPoint.getX(), (int)prevPoint.getY(), e.getX(), e.getY()); prevPoint = new Point(e.getX(), e.getY()); } public void mouseReleased(MouseEvent e) {} 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[]) { Scribbler2 s = new Scribbler2(); } };