Newer
Older
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
package shape;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseButton;
import java.util.ArrayList;
import java.util.List;
public class Drawer {
private List<Shape> shapes;
private double width;
private double height;
private Canvas canvas;
private GraphicsContext gc;
private Rectangle tempRectangle = null;
public Drawer(double width, double height) {
this.width = width;
this.height = height;
shapes = new ArrayList<>();
canvas = new Canvas(width,height);
gc = canvas.getGraphicsContext2D();
setupMouseHandlers();
}
public void add(Shape shape) {
shapes.add(shape);
}
public void repaint(){
gc.clearRect(0, 0, width, height);
for(Shape shape : shapes){
shape.paint(gc);
}
if (tempRectangle != null){
tempRectangle.paint(gc);
}
}
private void setupMouseHandlers(){
canvas.setOnMousePressed(event -> {
if(event.getButton() == MouseButton.PRIMARY){
double x = event.getX();
double y = event.getY();
tempRectangle = new Rectangle(x, y, 0, 0);
}
});
canvas.setOnMouseReleased(event -> {
if(event.getButton() == MouseButton.PRIMARY){
shapes.add(tempRectangle);
tempRectangle = null;
repaint();
}
});
}
public Shape shapeContaining(double x, double y){
for(Shape shape : shapes){
if (shape.contains(x, y)){
return shape;
}
}
return null;
}
public Canvas getCanvas() {
return canvas;
}
}