2013-12-10 53 views
-2

给出的以下代码的行:旋转使用鼠标在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.Double RECT =新Rectangle2D.Double(100,75,200,160); 到Line2D.Double rect = new Line2D.Double(100,75,200,160);以创建一条2D线。 之后,我应该如何修改代码,以便能够在线上获取鼠标的坐标,并使整个代码适用于线条的旋转。

谢谢!

+0

任何想法如何让它工作? – user3086760

回答

1

为了确定旋转你使用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()方法。

+0

是的, 想出了类似的解决方案。谢谢! – user3086760