1 | // Copyright 2004-2007 Jean-Francois Poilpret |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package net.sourceforge.hiveboard.drawing; |
16 | |
17 | import java.awt.Graphics2D; |
18 | import java.awt.Point; |
19 | import java.util.ArrayList; |
20 | import java.util.Iterator; |
21 | import java.util.List; |
22 | |
23 | import javax.swing.JComponent; |
24 | |
25 | public abstract class AbstractPenFreeTool extends AbstractMouseDragTool |
26 | { |
27 | public void start(JComponent area) |
28 | { |
29 | _area = area; |
30 | _points = new ArrayList<Point>(INITIAL_SIZE); |
31 | } |
32 | |
33 | public void mouseMotion(Point location) |
34 | { |
35 | boolean hasScrolled = scroll(_area, location); |
36 | _points.add(location); |
37 | feedback(hasScrolled); |
38 | } |
39 | |
40 | public DrawingAction stop() |
41 | { |
42 | // Convert points list into a DrawingAction |
43 | int[] x = new int[_points.size()]; |
44 | int[] y = new int[_points.size()]; |
45 | int i = 0; |
46 | for (Point pt: _points) |
47 | { |
48 | x[i] = pt.x; |
49 | y[i] = pt.y; |
50 | ++i; |
51 | } |
52 | _points.clear(); |
53 | return createAction(x, y); |
54 | } |
55 | |
56 | abstract protected DrawingAction createAction(int[] x, int[] y); |
57 | |
58 | abstract protected void preDraw(Graphics2D graf); |
59 | |
60 | protected void postDraw(Graphics2D graf) |
61 | { |
62 | } |
63 | |
64 | // This method provides immediate feedback to writer (not to other participants) |
65 | // by drawing the last segment recorded |
66 | private void feedback(boolean completeRedraw) |
67 | { |
68 | Graphics2D graf = (Graphics2D) _area.getGraphics(); |
69 | preDraw(graf); |
70 | if (completeRedraw) |
71 | { |
72 | Iterator<Point> iter = _points.iterator(); |
73 | Point pt1 = iter.next(); |
74 | while (iter.hasNext()) |
75 | { |
76 | Point pt2 = iter.next(); |
77 | graf.drawLine(pt1.x, pt1.y, pt2.x, pt2.y); |
78 | pt1 = pt2; |
79 | } |
80 | } |
81 | else |
82 | { |
83 | int size = _points.size(); |
84 | if (size >= 2) |
85 | { |
86 | Point pt1 = _points.get(size - 2); |
87 | Point pt2 = _points.get(size - 1); |
88 | graf.drawLine(pt1.x, pt1.y, pt2.x, pt2.y); |
89 | } |
90 | } |
91 | postDraw(graf); |
92 | graf.dispose(); |
93 | } |
94 | |
95 | protected JComponent _area; |
96 | protected List<Point> _points; |
97 | |
98 | static private final int INITIAL_SIZE = 500; |
99 | } |