展开全部
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import com.me.util.JFrameUtil;
public class SwingCar extends JFrame {
private final int rect_Width = 80;
private final int rect_Height = 50;
private final int radius = 15;
private final int arcAngle = 30;
private Point p = new Point();
public SwingCar() {
62616964757a686964616fe78988e69d8331333335316530setSize(500, 300);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrameUtil.toCenter(this);
p = new Point(getWidth() / 2, getHeight() / 2);
move();
}
@Override
public void paint(Graphics g) {
super.paint(g);
drawRect(p);
drawRolls(p);
g.drawLine(0,getHeight()/2+rect_Height/2+radius, getWidth(), getHeight()/2+rect_Height/2+radius);
}
public void drawRect(Point c) {
Graphics2D g = (Graphics2D) getGraphics();
g.setColor(Color.red);
g.drawRect((int) (c.getX() - rect_Width / 2),
(int) (c.getY() - rect_Height / 2), rect_Width, rect_Height);
g.setColor(Color.black);
g.drawLine((int) (c.getX() - rect_Width / 2)-50, (int) (c.getY() - rect_Height / 2)-rect_Height/2, (int) (c.getX() - rect_Width / 2), (int) (c.getY() - rect_Height / 2)+rect_Height/2);
g.setColor(Color.green);
g.fillOval((int) (c.getX() - rect_Width / 2)-50-2, (int) (c.getY() - rect_Height / 2)-rect_Height/2-2, 10, 10);
}
public void drawRolls(Point c) {
Graphics2D g = (Graphics2D) getGraphics();
g.setColor(Color.blue);
// first roll
g.fillOval((int) (c.getX() - rect_Width / 4 - radius), (int) (c.getY()
+ rect_Height / 2 - radius), radius * 2, radius * 2);
g.setColor(Color.green);
g.fillArc((int) (c.getX() - rect_Width / 4 - radius), (int) (c.getY()
+ rect_Height / 2 - radius), radius * 2, radius * 2,
calcAngle(c), arcAngle);
// second roll
g.setColor(Color.blue);
g.fillOval((int) (c.getX() + rect_Width / 4 - radius), (int) (c.getY()
+ rect_Height / 2 - radius), radius * 2, radius * 2);
g.setColor(Color.green);
g.fillArc((int) (c.getX() + rect_Width / 4 - radius), (int) (c.getY()
+ rect_Height / 2 - radius), radius * 2, radius * 2,
calcAngle(c), arcAngle);
}
public int calcAngle(Point c) {
Point center = new Point(getWidth() / 2, getHeight() / 2);
double distance = c.getX() - center.getX();
int angle = (int) (180 * distance / (Math.PI * radius));
return -angle;
}
public void move() {
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
p.translate(2, 0);
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
p.translate(-2, 0);
}
repaint();
}
});
}
public static void main(String[] args) {
SwingCar sc = new SwingCar();
}
}