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();
}
}