gpt4 book ai didi

java - 使用 Swing 制作交通动画

转载 作者:行者123 更新时间:2023-12-02 06:21:16 29 4
gpt4 key购买 nike

我一直在用 Java 编写交通模拟代码,现在想使用 swing 为模拟制作动画。我在主函数中调用 RoadNetwork 类,如下所示:

RoadNetwork roadnetwork = new RoadNetwork();

getcoords() 函数获取每个车辆的 xy 坐标位置,用于在 JPanel 上绘制车辆。我的主类的名字是AMEC。 spawned 变量显示车辆是否在模拟中生成,finished 变量指示车辆是否已退出模拟,vehiclecounter 变量显示整个模拟过程中的车辆总数,iconNumber 变量保存卡车图标表示车辆所在车辆的索引。分配给。

但是,当我运行主程序时,我没有收到任何视觉输出。我究竟做错了什么?另外,插入计时器并使用此程序更新我的 View 的最佳方法是什么?

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

最佳答案

"Also, what is the best way to insert a timer and updating my view with this program?"

使用javax.swing.Timer。基本结构很简单。这就像使用带有 ActionListener 的按钮,但 Timer 根据 持续时间每隔几毫秒触发 ActionEvent 你通过了。构造函数看起来像这样

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();
}
<小时/>

此外,无需在 paintComponent() 方法内调用 repaint()

关于java - 使用 Swing 制作交通动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20989860/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com