汽车运动演示

编写程序,模拟汽车运动。汽车从左向右移动。当它到达右终点,就从左边重新

开始,然后继续同样的过程。可以使用定时器控制动画。如下图所示:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CarSport extends JFrame {
  public CarSport() {
    add(new RaceCar());
  }
  public static void main(String[] args) {
    CarSport frame = new CarSport();
    frame.setTitle("CarSport");   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 100);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setVisible(true);
  }
}
class RaceCar extends JPanel {
  private int xBase = 0;
  private Timer timer = new Timer(1, new Listener());
  public RaceCar() {
    timer.start();
    this.setFocusable(true);
    // Control speed
    this.addKeyListener(new KeyAdapter() {
	  public void keyPressed(KeyEvent e) {
        if (e.isControlDown() && e.getKeyCode() == 61) {
	      if (timer.getDelay() > 5)
		    timer.setDelay(timer.getDelay() - 5);
		  }
		else if (e.isControlDown() && e.getKeyCode() == 45)
		  timer.setDelay(timer.getDelay() + 1);
	  }
    });
  }
  class Listener implements ActionListener {
    /** Handle ActionEvent */
    public void actionPerformed(ActionEvent e) {
     repaint();
    }
  }
  /** Paint message */
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int yBase = getHeight();
    if (xBase > getWidth())
      xBase = -20;
    else
      xBase += 1;
    g.setColor(Color.BLACK);
    g.fillOval(xBase + 10, yBase - 10, 10, 10);
    g.fillOval(xBase + 30, yBase - 10, 10, 10);
    g.setColor(Color.GREEN);
    g.fillRect(xBase, yBase - 20, 50, 10);
    g.setColor(Color.RED);
    Polygon polygon = new Polygon();
    polygon.addPoint(xBase + 10, yBase - 20);
    polygon.addPoint(xBase + 20, yBase - 30);
    polygon.addPoint(xBase + 30, yBase - 30);
    polygon.addPoint(xBase + 40, yBase - 20);
    g.fillPolygon(polygon);
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值