汽车运动演示

编程入门 行业动态 更新时间:2024-10-14 22:20:53

汽车运动<a href=https://www.elefans.com/category/jswz/34/1769411.html style=演示"/>

汽车运动演示

编写程序,模拟汽车运动。汽车从左向右移动。当它到达右终点,就从左边重新开始,然后继续同样的过程。可以使用定时器控制动画。如下图所示:





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

}
}

更多推荐

汽车运动演示

本文发布于:2024-02-25 19:15:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1700017.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:演示   汽车

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!