Drag rectangle on JFrame in Java

最后都变了- 提交于 2019-12-02 02:46:49

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<DrawnShape> drawings;
    private DrawnShape curShape;

    public DrawPane() {
        drawings = new ArrayList<DrawnShape>();
        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);
    }
}

Custom Painting Approaches shows two techniques for doing this.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!