import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;
public class Panel extends JPanel implements Runnable
{
int angle=0;
final int STEP=5;
final int INTERVAL=50;
public Panel()
{
}
@Override
public void run()
{
while (true)
{
try
{
Thread.sleep(INTERVAL);
}
catch (Exception e)
{
e.printStackTrace();
}
this.repaint();
}
}
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(0, 0, 400, 300);
this.drawTankAngle(100, 100, g, angle);
angle+=STEP;
}
private double getAngleByPoint(float x, float y)
{
return y>0 ? Math.acos(x/Math.sqrt(x*x+y*y)) : 2*Math.PI-Math.acos(x/Math.sqrt(x*x+y*y));
}
public void drawTankAngle(int x, int y, Graphics g, int angle)
{
int r=20;
//正方形
int[] xPoints={-r, r,r,-r};
int[] yPoints={-r, -r,r,r};
g.setColor(Color.yellow);
for(int i = 0; i < xPoints.length; i++)
{
float x1 = xPoints[i];
float y1 = yPoints[i];
double d=getAngleByPoint(x1,y1)+angle/360.0f*2*Math.PI;
xPoints[i]=(int)(Math.abs(xPoints[i]) * Math.cos(d));
yPoints[i]=(int)(Math.abs(yPoints[i]) * Math.sin(d));
xPoints[i] +=x;
yPoints[i] +=y;
}
g.drawString("0",x,y);
g.drawPolygon(xPoints, yPoints, xPoints.length);
g.drawOval(x-r, y-r, 2*r, 2*r);
}
}
运行效果图: