用鼠标移动和拉伸Line2D形状

时间:2015-09-11 17:45:04

标签: java swing mouseevent java-2d mouselistener

我想用鼠标移动并拉伸Line2D形状。我试过但面临一些问题。移动时突然向各个方向移动。我遇到了以下问题:

shape.setLine(p1,p2);

编辑:

早些时候我遇到了一些问题。

但我现在可以让它发挥作用,因此想在这里发帖。

public static void main(String [] args){         JFrame frame = new JFrame(“Lines”);

    frame.add(new JComponent() {
        private Shape line = null;
        {
            line = new Line2D.Double(100, 100, 200, 200);
            prevPoint = new Point();
            newPoint = new Point();

            MouseAdapter mouseAdapter = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    prevPoint = e.getPoint();
                    System.out.println("Prev Point=" + prevPoint.toString());
                    repaint();
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    int dx = 0;
                    int dy = 0;

                    dx = (int) (prevPoint.x - e.getPoint().getX());
                    dy = (int) (prevPoint.y - e.getPoint().getY());

                    Line2D shape = (Line2D) line;

                    int x1 = (int) (shape.getX1() - dx);
                    int y1 = (int) (shape.getY1() - dy);

                    int x2 = (int) (shape.getX2() - dx);
                    int y2 = (int) (shape.getY2() - dy);

                    Point startPoint = new Point(x1, y1);
                    Point endPoint = new Point(x2, y2);

                    if (shape != null) {
                        shape.setLine(startPoint, endPoint);
                        prevPoint = e.getPoint();
                        repaint();
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    repaint();
                }

            };
            addMouseListener(mouseAdapter);
            addMouseMotionListener(mouseAdapter);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setPaint(Color.BLUE);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            if (line != null) {
                g2d.draw(line);
            }
        }
    });
    frame.setSize(650, 400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

由于

0 个答案:

没有答案