2014-01-08 80 views
0

我一直在用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(); 
} 
} 
+1

什麼不顯示?卡車圖像? –

+0

我得到了框架來顯示,只是有setVisible和添加語法錯誤。謝謝! – Martin

回答

1

使用javax.swing.Timer。基本結構很簡單。這就像使用一個帶有ActionListener的按鈕,而是Timer根據您通過的duration每隔幾毫秒觸發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(); 
} 

而且持續時間,沒有必要打電話repaint()paintComponent()方法

+0

非常感謝。我會試一試,並嘗試發展你所提供的功能。 – Martin

+1

不要忘記調用'timer.start()' –

1

如果您需要在後臺執行任務,如動畫,則應使用Swingworker。這個類允許你在後臺執行一個長任務(在另一個線程中),並以一種將以正確線程執行的管理方式返回UI的變化。

http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

有人填補了很好的教程在這裏: 「?此外,什麼是插入一個計時器和更新我的看法與此程序的最佳途徑」

How do I use SwingWorker in Java?