您的位置:首页 > 编程语言 > Java开发

【java】java实现运动的小车

2016-10-24 00:50 162 查看


实现如图所示的运动的小车其实还是非常简单的,还是先来看一下源代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Car extends JFrame{

public Car(){
add(new MyCar());
}

public static void main(String[] args) {
Car frame = new Car();
frame.setTitle("Car race");
frame.setSize(400,100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class MyCar extends JPanel{

private int x = 10;

Timer time = new Timer(100,new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});

protected void paintComponent(Graphics g){
time.start();
super.paintComponent(g);

g.setColor(new Color(0, 0, 255));

g.fillOval(x, 50, 10, 10);
g.fillOval(x+20, 50, 10, 10);
g.fillRect(x-10, 40, 50, 10);

int [] xPoints = {x,x+10,x+20,x+30};
int [] yPoints = {40,30,30,40};
g.fillPolygon(xPoints, yPoints, 4);

x = x + 10;

if(x >= 400)
x = 10;
}
}
其中的fillPolygon方法是java中用于绘制多边形的方法,其参数为两个数组,第一个数组为多边形所有点的横坐标,第二个数组为多边形所有点的纵坐标,第三个参数为多边形点的个数,也就是那两个数组的长度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: