import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import javax.swing.event.MouseInputAdapter; /** * This class represents a drawing surface that can draw lines between points * where the user clicks the mouse. * @author Marty Stepp * @version CSE 331 Spring 2011, 05/11/2011 */ public class LineCanvas extends JComponent { private static final long serialVersionUID = 1L; private List clicks; // past points the user has clicked private Point mousePosition; // mouse pointer's current position /** * Constructs a new empty canvas with no lines. */ public LineCanvas() { clicks = new ArrayList(); mousePosition = null; // listen to mouse events LineClickListener listener = new LineClickListener(); addMouseListener(listener); addMouseMotionListener(listener); } /** * Draws all previously touched points and lines on this canvas. */ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; // draw previously clicked points as circles with lines between Point prev = null; for (Point p : clicks) { Ellipse2D dot = new Ellipse2D.Double(p.getX(), p.getY(), 5, 5); g2.fill(dot); if (prev != null) { // line between previous point and current point Line2D line = new Line2D.Double(prev, p); g2.draw(line); } prev = p; } // draw a hovering red line to the mouse's current position, if necessary if (mousePosition != null && !clicks.isEmpty()) { Point lastClick = clicks.get(clicks.size() - 1); Line2D line = new Line2D.Double(lastClick, mousePosition); g2.setColor(Color.RED); g2.draw(line); } } // This listener handles mouse events in the canvas. private class LineClickListener extends MouseInputAdapter { /** * Handles mouse clicks by drawing a new line to the point clicked. */ public void mouseClicked(MouseEvent e) { // System.out.println("The mouse was clicked"); // If the user double-clicks, add a point to draw a line if (e.getClickCount() >= 2) { clicks.add(e.getPoint()); repaint(); } } /** * Handles mouse clicks by showing a red hovering line from the * previous click point to the most recent point clicked. */ public void mouseMoved(MouseEvent e) { mousePosition = e.getPoint(); repaint(); } } }