演示"/>
汽车运动演示
编写程序,模拟汽车运动。汽车从左向右移动。当它到达右终点,就从左边重新开始,然后继续同样的过程。可以使用定时器控制动画。如下图所示:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test6 extends JFrame{
public Test6(){
add(new Car());
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test6 frame = new Test6();
frame.setSize(250, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Car extends JPanel{
private int direction = 1;
private int speed = 10;
private int x = 0;
protected Timer timer = new Timer(speed,new TimerListener());
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}
public Car(){
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int y =getHeight();
if(x>getWidth())
x=0;
else
x+=1;
g.setColor(Color.BLACK);
g.fillOval(x+10, y-10, 10, 10);
g.fillOval(x+30, y-10, 10, 10);
g.setColor(Color.GREEN);
g.fillRect(x, y-20, 50, 10);
g.setColor(Color.RED);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 20);
polygon.addPoint(x + 20, y - 30);
polygon.addPoint(x + 30, y - 30);
polygon.addPoint(x + 40, y - 20);
g.fillPolygon(polygon);
}
}
更多推荐
汽车运动演示
发布评论