package Scribble; import java.awt.event.*; import cs101.awt.Line; import java.awt.Color; /** * This class processes all mouse events for the scribble board. * This includes drawing lines on the SmartCanvas, clearing the * lines when the clear button is pressed, and changing the color * when the item list is changed. **/ public class MyMouseListener extends MouseAdapter implements MouseMotionListener, ActionListener, ItemListener { // Objects used to display and store the lines. private ScribbleData lines; private SmartCanvas drawArea; // Currently selected color private Color color; // Last place at which a mouse event occured with the button down. private int startX; private int startY; /** * Constructor for this listener. * @param lines ScribbleData which stores all lines. * @param drawArea SmartCanvas on which lines are drawn. **/ MyMouseListener(ScribbleData lines, SmartCanvas drawArea) { // Store references to the ScribbleData and SmartCanvas // used by the rest of the program. this.lines = lines; this.drawArea = drawArea; // Set the initial color to black. color = Color.black; } /** * Called when the mouse button is pressed. * When the button is pressed, start a new line from that point. **/ public void mousePressed(MouseEvent e) { this.startX = e.getX(); this.startY = e.getY(); // Draw a dot at that point. lines.addLine(new Line(this.startX, this.startY, this.startX, this.startY, this.color)); } /** * Called when the mouse is dragged (i.e. with the button down) * Draw a line from the last seen point to the location of * this event, and set the last seen point to the new location. **/ public void mouseDragged(MouseEvent e) { lines.addLine(new Line(this.startX, this.startY, e.getX(), e.getY(), this.color)); this.startX = e.getX(); this.startY = e.getY(); } /** * Called when the mouse is moved (i.e. without the button down) * Does nothing. **/ public void mouseMoved(MouseEvent e) { } /** * Called when the clear button is pressed. * Clears all lines from the ScribbleData **/ public void actionPerformed(ActionEvent e) { lines.clearLines(); } /** * Called when the color selection is changed. * Set the current drawing color to the new specified * color. **/ public void itemStateChanged(ItemEvent e) { this.color = cs101.util.Coerce.StringToColor((String)e.getItem()); } }