Drag rectangle on JFrame in Java

后端 未结 2 530
长情又很酷
长情又很酷 2021-01-24 06:43

I want to draw rectangle based on mousedrag event. if user dragging the mouse, then the rectangle on the applet should increase or decrease basing on current mouse coordinates.

2条回答
  •  时光说笑
    2021-01-24 07:05

    What you need to do, is save the previously drawn rectangle in some sort of data structure, so you can draw it again later.

    This code (sorry about the length, will do something similar to what you are describing.
    To use it, just slap the JPanel inside of a JFrame.

    public class DrawPane extends JPanel {
    
        private List drawings;
        private DrawnShape curShape;
    
        public DrawPane() {
            drawings = new ArrayList();
            setBackground(Color.WHITE);
            setPreferredSize(new Dimension(300, 300));
            addMouseListener(clickListener);
            addMouseMotionListener(moveListener);
        }
    
        @Override
        protected void paintComponent(Graphics g2) {
            super.paintComponent(g2);
            Graphics2D g = (Graphics2D) g2;
            for (DrawnShape s : drawings) {
                s.draw(g);
            }
            g.setColor(Color.BLACK);
            g.setStroke(new BasicStroke(2));
    
            if (curShape == null)
                return;
            curShape.draw(g);
        }
    
        private MouseListener clickListener = new MouseAdapter() {
    
            @Override
            public void mousePressed(MouseEvent e) {
                curShape = new DrawnShape(e.getPoint(), e.getPoint());
            }
    
            @Override
            public void mouseReleased(MouseEvent e) {
                drawings.add(new DrawnShape(curShape.getClickP(), e.getPoint()));
                curShape = null;
            }
        };
    
        private MouseMotionListener moveListener = new MouseMotionListener() {
    
            @Override
            public void mouseDragged(MouseEvent e) {
                curShape = new DrawnShape(curShape.getClickP(), e.getPoint());
                repaint();
            }
            @Override
            public void mouseMoved(MouseEvent e) {
            }
        };
    }
    
    class DrawnShape {
    
        private Point p1, p2;
    
        public DrawnShape(Point p1, Point p2) {
            this.p1 = p1;
            this.p2 = p2;
        }
    
        public Point getClickP() {
            return p1;
        }
    
        public void draw(Graphics2D g) {
            g.drawLine(p1.x, p1.y, p2.x, p1.y);
            g.drawLine(p1.x, p1.y, p1.x, p2.y);
            g.drawLine(p2.x, p2.y, p2.x, p1.y);
            g.drawLine(p2.x, p2.y, p1.x, p2.y);
        }
    }
    

提交回复
热议问题