public class ScribbleCanvas extends JPanel
1:
2: package scribble2;
3:
4: import java.awt.Color;
5: import java.awt.Dimension;
6: import java.awt.Graphics;
7: import java.awt.Point;
8: import java.util.*;
9: import java.io.*;
10: import java.awt.event.*;
11: import java.util.EventListener;
12: import javax.swing.*;
13:
14: public class ScribbleCanvas extends JPanel {
15:
16: public ScribbleCanvas() {
17: listener = new ScribbleCanvasListener(this);
18: addMouseListener((MouseListener) listener);
19: addMouseMotionListener((MouseMotionListener) listener);
20: }
21:
22: public void setCurColor(Color curColor) {
23: this.curColor = curColor;
24: }
25:
26: public Color getCurColor() {
27: return curColor;
28: }
29:
30: public void startStroke(Point p) {
31: curStroke = new Stroke(curColor);
32: curStroke.addPoint(p);
33: }
34:
35: public void addPointToStroke(Point p) {
36: if (curStroke != null) {
37: curStroke.addPoint(p);
38: }
39: }
40:
41: public void endStroke(Point p) {
42: if (curStroke != null) {
43: curStroke.addPoint(p);
44: strokes.add(curStroke);
45: curStroke = null;
46: }
47: }
48:
49: public void paint(Graphics g) {
50: Dimension dim = getSize();
51: g.setColor(Color.white);
52: g.fillRect(0, 0, dim.width, dim.height);
53: g.setColor(Color.black);
54: if (strokes != null) {
55: Iterator iter1 = strokes.iterator();
56: while (iter1.hasNext()) {
57: Stroke stroke = (Stroke) iter1.next();
58: if (stroke != null) {
59: g.setColor(stroke.getColor());
60: Point prev = null;
61: List points = stroke.getPoints();
62: Iterator iter2 = points.iterator();
63: while (iter2.hasNext()) {
64: Point cur = (Point) iter2.next();
65: if (prev != null) {
66: g.drawLine(prev.x, prev.y, cur.x, cur.y);
67: }
68: prev = cur;
69: }
70: }
71: }
72: }
73: }
74:
75: public void newFile() {
76: strokes.clear();
77: repaint();
78: }
79:
80: public void openFile(String filename) {
81: try {
82: ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
83: strokes = (List) in.readObject();
84: in.close();
85: repaint();
86: } catch (IOException e1) {
87: System.out.println("Unable to open file: " + filename);
88: } catch (ClassNotFoundException e2) {
89: System.out.println(e2);
90: }
91: }
92:
93: public void saveFile(String filename) {
94: try {
95: ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
96: out.writeObject(strokes);
97: out.close();
98: System.out.println("Save drawing to " + filename);
99: } catch (IOException e) {
100: System.out.println("Unable to write file: " + filename);
101: }
102: }
103:
104: // The list of strokes of the drawing
105: // The elements are instances of Stroke
106: protected List strokes = new ArrayList();
107:
108: protected Stroke curStroke = null;
109: protected Color curColor = Color.black;
110:
111: protected EventListener listener;
112: protected boolean mouseButtonDown = false;
113: protected int x, y;
114:
115: }
116: