我一直在用Java編寫交通模擬,現在想用swing來模擬動畫。我打電話RoadNetwork類在我的主要功能如下:Swing交通動畫
RoadNetwork roadnetwork = new RoadNetwork();
()函數獲取每輛車的爲XY座標用於在JPanel中繪製車輛位置的getcoords。我的主要班級的名字是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();
}
}
什麼不顯示?卡車圖像? –
我得到了框架來顯示,只是有setVisible和添加語法錯誤。謝謝! – Martin