Skip to content
Snippets Groups Projects
Drawer.java 2.04 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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;
    
    MANSOUR Chadi's avatar
    MANSOUR Chadi committed
    //    private double width;
    //    private double height;
    
        private Canvas canvas;
        private GraphicsContext gc;
    
        private Rectangle tempRectangle = null;
    
        public Drawer(double width, double height) {
    
    MANSOUR Chadi's avatar
    MANSOUR Chadi committed
    //        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(){
    
    MANSOUR Chadi's avatar
    MANSOUR Chadi committed
            gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
    
            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);
                }
            });
    
    MANSOUR Chadi's avatar
    MANSOUR Chadi committed
    
            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);
                    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;
        }
    }