public class ScribbleCanvas extends JPanel
1:
2: package scribble3;
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: // calling factory method
18: listener = makeCanvasListener();
19: addMouseListener((MouseListener) listener);
20: addMouseMotionListener((MouseMotionListener) listener);
21: }
22:
23: public void setCurColor(Color curColor) {
24: this.curColor = curColor;
25: }
26:
27: public Color getCurColor() {
28: return curColor;
29: }
30:
31: public void addShape(Shape shape) {
32: if (shape != null) {
33: shapes.add(shape);
34: }
35: }
36:
37: public void paint(Graphics g) {
38: Dimension dim = getSize();
39: g.setColor(Color.white);
40: g.fillRect(0, 0, dim.width, dim.height);
41: g.setColor(Color.black);
42: if (shapes != null) {
43: Iterator iter = shapes.iterator();
44: while (iter.hasNext()) {
45: Shape shape = (Shape) iter.next();
46: if (shape != null) {
47: shape.draw(g);
48: }
49: }
50: }
51: }
52:
53: public void newFile() {
54: shapes.clear();
55: repaint();
56: }
57:
58: public void openFile(String filename) {
59: try {
60: ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
61: shapes = (List) in.readObject();
62: in.close();
63: repaint();
64: } catch (IOException e1) {
65: System.out.println("Unable to open file: " + filename);
66: } catch (ClassNotFoundException e2) {
67: System.out.println(e2);
68: }
69: }
70:
71: public void saveFile(String filename) {
72: try {
73: ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
74: out.writeObject(shapes);
75: out.close();
76: System.out.println("Save drawing to " + filename);
77: } catch (IOException e) {
78: System.out.println("Unable to write file: " + filename);
79: }
80: }
81:
82: // factory method
83: protected EventListener makeCanvasListener() {
84: return new ScribbleCanvasListener(this);
85: }
86:
87: // The list of shapes of the drawing
88: // The elements are instances of Stroke
89: protected List shapes = new ArrayList();
90:
91: protected Color curColor = Color.black;
92:
93: protected EventListener listener;
94:
95: public boolean mouseButtonDown = false;
96: public int x, y;
97:
98: }
99: