Skip to content
Snippets Groups Projects
Commit 00d017b8 authored by MANSOUR Chadi's avatar MANSOUR Chadi
Browse files

drawing rectangle done

parent ed11c01f
No related branches found
No related tags found
No related merge requests found
......@@ -17,24 +17,9 @@ public class App extends Application {
public void start(Stage primaryStage) {
Drawer drawer = new Drawer(400, 400);
Circle circle = new Circle(200, 200, 50);
Rectangle rectangle = new Rectangle(100, 100, 150, 100);
drawer.add(circle);
drawer.add(rectangle);
drawer.repaint();
drawer.getCanvas().setOnMouseClicked(event -> {
double mouseX = event.getX();
double mouseY = event.getY();
Shape clickedShape = drawer.shapeContaining(mouseX, mouseY);
if (clickedShape != null) {
System.out.println("Shape clicked: " + clickedShape);
}
});
Group root = new Group();
root.getChildren().add(drawer.getCanvas());
Scene scene = new Scene(root, 400, 400);
primaryStage.setTitle("JavaFX Drawer");
......
......@@ -10,16 +10,16 @@ import java.util.List;
public class Drawer {
private List<Shape> shapes;
private double width;
private double height;
// 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;
// this.width = width;
// this.height = height;
shapes = new ArrayList<>();
canvas = new Canvas(width,height);
gc = canvas.getGraphicsContext2D();
......@@ -30,7 +30,7 @@ public class Drawer {
shapes.add(shape);
}
public void repaint(){
gc.clearRect(0, 0, width, height);
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
for(Shape shape : shapes){
shape.paint(gc);
}
......@@ -47,6 +47,16 @@ public class Drawer {
tempRectangle = new Rectangle(x, y, 0, 0);
}
});
canvas.setOnMouseDragged(event ->{
if (tempRectangle != null) {
double x = event.getX();
double y = event.getY();
tempRectangle.updateSize(x,y);
repaint();
}
});
canvas.setOnMouseReleased(event -> {
if(event.getButton() == MouseButton.PRIMARY){
shapes.add(tempRectangle);
......
......@@ -20,6 +20,7 @@ public class Rectangle implements Shape{
@Override
public void paint(GraphicsContext graphicsContext) {
graphicsContext.setStroke(Color.BLACK);
graphicsContext.strokeRect(x, y, width, height);
}
......@@ -35,4 +36,12 @@ public class Rectangle implements Shape{
x += dx;
y += dy;
}
public void updateSize(double newX, double newY) {
this.width = Math.abs(newX - this.x);
this.height = Math.abs(newY - this.y);
if (newX < this.x && newY < this.y) {
this.x = newX;
this.y = newY;
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment