public class TwoEndsTool extends AbstractTool
1:
2: package draw1;
3:
4: import java.awt.*;
5: import scribble3.*;
6:
7: public class TwoEndsTool extends AbstractTool {
8:
9: public static final int LINE = 0;
10: public static final int OVAL = 1;
11: public static final int RECT = 2;
12:
13: public TwoEndsTool(ScribbleCanvas canvas, String name, int shape) {
14: super(canvas, name);
15: this.shape = shape;
16: }
17:
18: public void startShape(Point p) {
19: canvas.mouseButtonDown = true;
20: xStart = canvas.x = p.x;
21: yStart = canvas.y = p.y;
22: Graphics g = canvas.getGraphics();
23: g.setXORMode(Color.darkGray);
24: g.setColor(Color.lightGray);
25: switch (shape) {
26: case LINE:
27: drawLine(g, xStart, yStart, xStart, yStart);
28: break;
29: case OVAL:
30: drawOval(g, xStart, yStart, 1, 1);
31: break;
32: case RECT:
33: drawRect(g, xStart, yStart, 1, 1);
34: break;
35: }
36: }
37:
38: public void addPointToShape(Point p) {
39: if (canvas.mouseButtonDown) {
40: Graphics g = canvas.getGraphics();
41: g.setXORMode(Color.darkGray);
42: g.setColor(Color.lightGray);
43: switch (shape) {
44: case LINE:
45: drawLine(g, xStart, yStart, canvas.x, canvas.y);
46: drawLine(g, xStart, yStart, p.x, p.y);
47: break;
48: case OVAL:
49: drawOval(g, xStart, yStart, canvas.x - xStart + 1, canvas.y - yStart + 1);
50: drawOval(g, xStart, yStart, p.x - xStart + 1, p.y - yStart + 1);
51: break;
52: case RECT:
53: drawRect(g, xStart, yStart, canvas.x - xStart + 1, canvas.y - yStart + 1);
54: drawRect(g, xStart, yStart, p.x - xStart + 1, p.y - yStart + 1);
55: break;
56: }
57: canvas.x = p.x;
58: canvas.y = p.y;
59: }
60: }
61:
62: public void endShape(Point p) {
63: canvas.mouseButtonDown = false;
64: TwoEndsShape newShape = null;
65: switch (shape) {
66: case LINE:
67: newShape = new LineShape();
68: break;
69: case OVAL:
70: newShape = new OvalShape();
71: break;
72: case RECT:
73: newShape = new RectangleShape();
74: }
75: if (newShape != null) {
76: newShape.setColor(canvas.getCurColor());
77: newShape.setEnds(xStart, yStart, p.x, p.y);
78: canvas.addShape(newShape);
79: }
80: Graphics g = canvas.getGraphics();
81: g.setPaintMode();
82: canvas.repaint();
83: }
84:
85: protected int shape = LINE;
86: protected int xStart, yStart;
87:
88: // helper methods
89: public static void drawLine(Graphics g, int x1, int y1, int x2, int y2) {
90: g.drawLine(x1, y1, x2, y2);
91: }
92:
93: public static void drawRect(Graphics g, int x, int y, int w, int h) {
94: if (w < 0) {
95: x = x + w;
96: w = -w;
97: }
98: if (h < 0) {
99: y = y + h;
100: h = -h;
101: }
102: g.drawRect(x, y, w, h);
103: }
104:
105: public static void drawOval(Graphics g, int x, int y, int w, int h) {
106: if (w < 0) {
107: x = x + w;
108: w = -w;
109: }
110: if (h < 0) {
111: y = y + h;
112: h = -h;
113: }
114: g.drawOval(x, y, w, h);
115: }
116:
117: }