2011-12-07 48 views
3

我..我有一個形象畫在我的Java Applet和一個for循環,使X向上移動5每次一個問題..但它留下的舊形象背後一下,然後它會刪除它..Java的圖像油漆問題

for(int tohouse = 0; tohouse <= 520; tohouse+=2) { 
    try { 
    x+=5; 
    tohouse+=10; 

    if (pos == 0) { 
     rectX+=5; 
     g.drawImage(picture1,x,150,this); 
     pos = 1; 
    } else if (pos == 1) { 
     rectX+=4; 
     g.drawImage(picture2,x,150,this); 
     pos = 2; 
    } else if (pos == 2) { 
     rectX+=5; 
     g.drawImage(picture3,x,150,this); 
     pos = 0; 
    } 
    } 
} 

繼承人圖像:

Image

+0

哪些不使用switch語句而不是所有這些ifs和elses? – PTBG

+0

我忘了那些謝謝!這是我的計算機科奇AP類的項目..我要修復它來切換語句。 –

+0

您需要停下來掌握圖形遊戲的基本解剖。你需要學習的絕對第一課是*渲染*圖形和*改變遊戲狀態*應該是獨立的操作,無論是在時間上還是在代碼的放置位置。看看http://www.theopavlidis.com/Games/Tutorial_Draft_01/part00.htm(我可以找到第一個結果)。通過在繪製方法中放置for循環,您無法做動畫。 –

回答

3

你不能在你的paintComponent()paint()方法循環做動畫。這些方法都在問,你在時間上特定點(即當前幀)畫自己。

相反,你需要從「渲染」你的精靈脫鉤「動」你的精靈的邏輯。尋找像這樣的東西

private int x; 

protected void paintComponent(Graphics g) { 
    //draw the images at location x 
} 

// elsewhere, initialize a javax.swing.Timer to increment x every 15 ms 
new Timer(15, new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     x += 5; 
     repaint(); 
    } 
}.start(); 
0

試試這個:

for(int tohouse = 0; tohouse <= 520; tohouse+=2) 
{ 
    try 
    { 
     switch(pos){ 
     case 0: 
      rectX+=5; 
      g.drawImage(picture1,x,150,this); 
      pos = 1; 
      break; 
     case 1: 
       rectX+=4; 
       g.drawImage(picture2,x,150,this); 
       pos = 2; 
      break; 
     case 2: 
      rectX+=5; 
      g.drawImage(picture3,x,150,this); 
      pos = 0; 
      break; 
     default: // add some default behavior here 
      break; 
     } 
    } catch(Exception e){ 
     // do something 
    } 
} 
0

ÿ你需要告訴java重新繪製框架。'

上只要用你的repaint()JComponent該圖像是在的結束for循環。就像這樣:

for(int tohouse = 0; tohouse <= 520; tohouse+=2) { 
    try { 
    //Process the changes 
    } 
    component.repaint(); // where component is what the image is added to. 
} 
+0

因爲邏輯是中*他的paint方法是行不通*。 –

+0

他從來沒有說過它是在'paint()'方法中。在這一點上真的沒有辦法做到這一點。甚至在paint()裏面,重繪父組件仍然可以正常工作(通常)。 – Jon

+0

不,它不會。在paint()內部,你處於事件調度線程的事件中,因此所有的repaint()調用都會排隊等待,並且只有在方法運行完成後才能處理。 –