我一直在用Java编写一个流量模拟程序,现在我想用swing来动画模拟。我在我的主要函数中调用RoadNetwork类如下所示:
RoadNetwork roadnetwork = new RoadNetwork();函数获取每个车辆作为xy坐标的位置,用于绘制JPanel上的车辆。我的主要班级名是AMEC。生成变量表示车辆是否在仿真中产生,成品变量表示是否退出了仿真,车辆测定器变量显示整个仿真过程中的车辆总数,iconNumber变量保存truckIcon所述车辆被分配给的指标。
然而,当我运行我的主程序,我没有收到任何视觉输出。我做错了什么?另外,使用这个程序插入计时器和更新我的视图的最佳方法是什么?
public class RoadNetwork extends JPanel {
// create array size of the amount of trucks generated
BufferedImage truckicons[] = new BufferedImage[100];
int populated[] = new int[100]; // array that indicates the identifier of the truck occupying the corresponding position in truckicons[]
public RoadNetwork() throws IOException{
for (int i = 0; i < 100; i++) {
populated[i] = -1; // initialization value
truckicons[i] = ImageIO.read(getClass().getResource("Truck.png")); // assign icon to each truck
}
}
protected void paintComponent (Graphics g) {
super.paintComponent(g);
int coords[] = new int[2];
for (int i = 0; i < 100; i++) {
if (populated[i] != -1) {
coords = AMEC.getcoord(populated[i]);
g.drawImage(truckicons[i], coords[0], coords[1], this);
}
}
for (int k = 0; k < AMEC.vehiclecounter; k++) {
if (AMEC.vehicle[k].spawned == true && AMEC.vehicle[k].finished == false) { // if the truck is somewhere on the plant
if (AMEC.vehicle[k].iconNumber == -1) { // if the vehicle hasn't been assigned an icon yet
for (int l = 0; l < 100; l++) {
if (populated[l] == -1) {
populated[l] = k;
AMEC.vehicle[k].iconNumber = l;
break;
}
}
}
}
else if (AMEC.vehicle[k].spawned == true && AMEC.vehicle[k].finished == true && AMEC.vehicle[k].iconNumber != -1) { // if the vehicle is done but hasn't been cleared from the icon list yet
populated[AMEC.vehicle[k].iconNumber] = -1;
AMEC.vehicle[k].iconNumber = -1;
}
}
this.repaint();
}
}发布于 2014-01-08 08:03:05
“另外,用这个程序插入计时器和更新我的视图的最佳方法是什么?”
使用javax.swing.Timer。基本结构简单。这就像使用带有ActionListener的按钮一样,但是Timer每隔这么多毫秒就会触发ActionEvent,这是基于您传递的duration。构造函数如下所示
Timer(int duration, ActionListener)因此,示例用法应该是这样的,其中50是每个事件被触发的持续时间。
public RoadNetwork() {
Timer timer = new Timer(50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do something with image positions like loop through an array to move coordinates
repaint();
}
});
timer.start();
}此外,不需要在repaint()方法中调用paintComponent()
发布于 2014-01-08 08:02:59
如果需要在后台执行任务,如动画,则应使用Swingworker。这个类允许您在后台(在另一个线程中)执行一个长任务,并以将在正确线程中执行的托管方式返回对UI的更改。
http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
有人在这里填写了一个很好的教程:
https://stackoverflow.com/questions/20989860
复制相似问题