实现图片随鼠标转动

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * @author Lei
 * @version create time:2009-9-11 下午02:16:01
 */
public class Frame extends JFrame {
 JPanel jPanel = new RotateImage();
 public static void main(String[] args) {
  new Frame();
 }
 public Frame() {
  this.add(jPanel);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setVisible(true);
  this.setBounds(100 , 100, 800, 800);
 }
}
class RotateImage extends JPanel implements MouseMotionListener {
 BufferedImage bufferedimage;
 double degree = 0;
 int x = 100;
 int y = 100;
 int w = 0;
 int h = 0;
 //已知两点求斜率
 public double toSlope(Point point1, Point point2) {
  double x1 = point1.getX();
  double y1 = point1.getY();
  double x2 = point2.getX();
  double y2 = point2.getY();
  double slope = 0;
  if(x1 != x2) {
   slope = (y2 - y1) / (x2 - x1);
  }
//  System.out.println(slope);
  return slope;
 }
 
 //已知斜率求弧度
 
 public double toRadian(double slope) {
  double radian = Math.atan(slope);
  return radian;
 }
 
 //已知弧度求角度
 public double toDegree(double radian) {
  degree = 180 * radian /Math.PI ;
//  System.out.println(degree);
  return degree;
 }
 
 public RotateImage() {
  try {
   bufferedimage = ImageIO.read(new File("tankR.gif"));
  }
  catch (IOException e) {
   e.printStackTrace();
  }
  this.addMouseMotionListener(this);
 }
 @Override
 public void paintComponent(Graphics g) {
  super.paintComponent(g);
  w = bufferedimage.getWidth();
  h = bufferedimage.getHeight();
  ((Graphics2D) g).rotate(Math.toRadians(degree), x + w / 2, y + h / 2);
        g.drawImage(bufferedimage, x, y, null);
 }

 @Override public void mouseDragged(MouseEvent e) {
 }

 @Override public void mouseMoved(MouseEvent e) {
  Point point1 = new Point(x + w/2, y + h/2);
  Point point2 = e.getPoint();
//  System.out.println(point2.x+ "-----------" + point2.y);
  if(point2.x > point1.x) {
   double slope = this.toSlope(point1, point2);
   double radian = this.toRadian(slope);
   degree = this.toDegree(radian);
  }
  else if(point2.x < point1.x) {
   double slope = this.toSlope(point1, point2);
   double radian = this.toRadian(slope);
   degree = this.toDegree(radian + Math.PI);
  }
  else {
   if(point1.y > point2.y) {
    degree = 270;
   }
   else if (point1.y < point2.y) {
    degree = 90;
   }
   else {
    degree = 0;
   }
   
  }
  repaint();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值