import javax.swing.*; import javax.swing.plaf.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; /** * The DrawPanel contains everything for creating a drawing * * @author Stuart Hansen * @version December 22, 2000 * modified October 16, 2001 -- added alternative colors * modified February 5, 2002 -- made resizing work * modified February 4, 2003 -- changed to drawing with lines */ public class DrawPanel extends JPanel implements Serializable { Vector vectorOfCurves; // the drawing is a vector of curves Vector currentCurve; // the current curve being drawn Color currentColor; // the current drawing color /** the constructor sets up the panel */ public DrawPanel () { vectorOfCurves = new Vector(); setBackground(Color.white); currentColor = Color.black; setUI(new DrawPanelUI()); addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } /** get the current color */ public Color getCurrentColor () { return currentColor; } /** set the current color */ public void setCurrentColor (Color c) { currentColor = c; } /** clear the drawing */ public void clear () { vectorOfCurves = new Vector(); repaint(); } /** This inner class knows how to draw the DrawPanel */ class DrawPanelUI extends ComponentUI { public void paint (Graphics g, JComponent c) { // We iterate across the Vector of curves, drawing each Iterator curvesIterator = vectorOfCurves.iterator(); while (curvesIterator.hasNext()) { // We iterate across each curve drawing it Vector curve = (Vector)curvesIterator.next(); Iterator oneCurveIterator = curve.iterator(); // The first thing in a curve is its color g.setColor((Color)oneCurveIterator.next()); // The remainder of the curve is a sequence of Points Point p1 = (Point) oneCurveIterator.next(); while (oneCurveIterator.hasNext()) { Point p2 = (Point) oneCurveIterator.next(); g.drawLine((int)p1.getX(), (int)p1.getY(), (int)p2.getX(), (int)p2.getY()); p1 = p2; } } } } /** This adds points to the current vector */ private class MouseMotionHandler extends MouseMotionAdapter{ public void mouseDragged (MouseEvent e){ if (SwingUtilities.isLeftMouseButton(e)){ currentCurve.add(e.getPoint()); repaint(); } } } /** When the mouse is pressed a new curve is started */ private class MouseHandler extends MouseAdapter { public void mousePressed (MouseEvent e) { currentCurve = new Vector(); currentCurve.add(currentColor); currentCurve.add(e.getPoint()); vectorOfCurves.add(currentCurve); } } }