/
DrawLineTool.java
100 lines (84 loc) · 2.28 KB
/
DrawLineTool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package WhiteBoard;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
public class DrawLineTool extends JButton implements MouseListener, MouseMotionListener
{
private DrawingBoard board;
private BufferedImage canvas, oldCanvas;
private int x, y, prevX, prevY;
private Graphics2D g2;
public DrawLineTool(DrawingBoard _board)
{
super("Line");
board = _board;
this.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
setListeners();
}
});
}
private void setListeners()
{
board.removeListeners();
board.setListeners(this, this);
}
@Override
public void mouseClicked(MouseEvent e)
{
//Does Nothing
}
@Override
public void mousePressed(MouseEvent e)
{
//Sets the start coordinates and gets a copy of the canvas to be saved
//as a backup
prevX = e.getX();
prevY = e.getY();
oldCanvas = board.getCanvas();
}
@Override
public void mouseReleased(MouseEvent e)
{
//Sends the drawn line through the network
board.sendCanvas();
}
@Override
public void mouseEntered(MouseEvent e)
{
//Does Nothing
}
@Override
public void mouseExited(MouseEvent e)
{
//Does Nothing
}
@Override
public void mouseDragged(MouseEvent e)
{
//Gets the canvas and graphics
canvas = board.getCanvas();
g2 = (Graphics2D) canvas.getGraphics();
g2.setColor(board.getColor());
g2.setStroke(board.getStroke());
x = e.getX();
y = e.getY();
//Clears the image by drawing the old saved copy, then draws a new line.
g2.drawImage(oldCanvas, 0, 0, this);
g2.drawLine(prevX, prevY, x, y);
board.updateCanvas(canvas);
}
@Override
public void mouseMoved(MouseEvent e)
{
//Does Nothing
}
}