在Java中使用鼠标旋转一条线

时间:2013-12-10 12:16:31

标签: java swing graphics rotation line

给出以下代码:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;

public class DragRotation extends JPanel {
Rectangle2D.Double rect = new Rectangle2D.Double(100,75,200,160);
AffineTransform at = new AffineTransform();

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(Color.blue);
    g2.draw(rect);
    g2.setPaint(Color.red);
    g2.draw(at.createTransformedShape(rect));
}

public static void main(String[] args) {
    DragRotation test = new DragRotation();
    test.addMouseListener(test.rotator);
    test.addMouseMotionListener(test.rotator);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(test);
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
}

private MouseInputAdapter rotator  = new MouseInputAdapter() {
    Point2D.Double center = new Point2D.Double();
    double thetaStart = 0;
    double thetaEnd = 0;
    boolean rotating = false;

    public void mousePressed(MouseEvent e) {
        Point p = e.getPoint();
        Shape shape = at.createTransformedShape(rect);
        if(shape.contains(p)) {
            Rectangle r = shape.getBounds();
            center.x = r.getCenterX();
            center.y = r.getCenterY();
            double dy = p.y - center.y;
            double dx = p.x - center.x;
            thetaStart = Math.atan2(dy, dx) - thetaEnd;
            System.out.printf("press thetaStart = %.1f%n",
                               Math.toDegrees(thetaStart));
            rotating = true;
        }
    }

    public void mouseReleased(MouseEvent e) {
        rotating = false;
        double dy = e.getY() - center.y;
        double dx = e.getX() - center.x;
        thetaEnd = Math.atan2(dy, dx) - thetaStart;
        System.out.printf("release thetaEnd = %.1f%n",
                           Math.toDegrees(thetaEnd));
    }

    public void mouseDragged(MouseEvent e) {
        if(rotating) {
            double dy = e.getY() - center.y;
            double dx = e.getX() - center.x;
            double theta = Math.atan2(dy, dx);
            at.setToRotation(theta - thetaStart, center.x, center.y);
            repaint();
        }
    }
};
}

如果我改变了行:Rectangle2D.Double rect = new Rectangle2D.Double(100,75,200,160); to Line2D.Double rect = new Line2D.Double(100,75,200,160);为了创建2D线。 之后我应该如何修改代码,以便能够在线上获得鼠标的坐标,并使整个代码适用于线的旋转。

谢谢!

1 个答案:

答案 0 :(得分:1)

对于确定旋转,你使用shape.contains(p)它适用于Rectangle,但它不适用于一行,因为我认为很难指向一行。

你需要为一条线的旋转标志指定一些区域,如下所示:

if(rect.x1 < p.x && rect.x2 > p.x 
        && rect.y1 < p.y && rect.y2 > p.y){
}

而不是

if(shape.contains(p)) {
}

mousePressed()方法中。