使用Java中的鼠标旋转一行



给定以下代码:

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.DDouble rect=new Rectangle2D。Double(100,75200160);到Line2D.DDouble rect=新的Line2D.Double(100,75200160);以便创建2D线。之后,我应该如何修改代码,以便它能够获得鼠标在直线上的坐标,并使整个代码为直线的旋转工作。

谢谢!

对于确定旋转,您使用shape.contains(p),它适用于矩形,但不适用于直线,因为我认为指向直线内部真的很难。

你需要为一行的旋转标志指定一些区域,比如下一个:

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

而不是

if(shape.contains(p)) {
}

在您的mousePressed()方法中。

相关内容

  • 没有找到相关文章

最新更新