2011-05-06 69 views
0

我正在編寫一個程序,它將播放一首歌曲並在其中顯示一個JPanel圖像。歌曲播放良好,第一個圖像被繪製(我從最初調用paintComponent時假定),但不知何故repaint()似乎沒有被調用。我真的可以使用額外的眼睛。我有下面的代碼來顯示圖像的JPanel類。非常感謝!在JPanel Runnable中重繪問題

class pictures extends JPanel implements Runnable { 
private ImageIcon images[]; 
private Thread imagerunner; 
private int currentImage; 

pictures() { 
    super(); 
    imagerunner = new Thread(this); 
    images = new ImageIcon[6]; 
    imagerunner = new Thread(this); 
    images[0] = new ImageIcon("pic1.jpg"); 
    images[1] = new ImageIcon("pic2.jpg"); 
    images[2] = new ImageIcon("pic3.jpg"); 
    images[3] = new ImageIcon("pic4.jpg"); 
    images[4] = new ImageIcon("pic5.jpg"); 
    images[5] = new ImageIcon("pic6.jpg"); 
    currentImage = 0; 
} 

public void run() { 
    int i = 0; 
    System.out.println("starting pics"); 
    while(i < 100) { 
     System.out.println("about to repaint()"); 
     this.repaint(); 
     System.out.println("image: " + currentImage); 
     waiting(2000); 
     currentImage++; 
    } 
    System.out.println("done"); 
} 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    System.out.println("repainting"); 
    images[ currentImage ].paintIcon(this,g,0,0); 
} 

public static void waiting (int n) { 
    long t0, t1; 
    t0 = System.currentTimeMillis(); 
    do{ 
     t1 = System.currentTimeMillis(); 
    } 
    while (t1 - t0 < n); 
} 
} 
+1

你如何稱此類的代碼?你在哪裏打電話給你的線程啓動()? – 2011-05-06 05:36:55

+0

爲了更快提供更好的幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。順便說一句 - 當currentImage計數器達到6時,你會發生什麼? – 2011-05-06 05:39:40

回答

0
  1. 你永遠不啓動線程imagerunner
  2. 它被分配兩次(無理由)。
  3. 您無法從其他線程修改GUI。爲此,使用Swing utilities
0

waiting()方法似乎阻止了EDT。使用Swing Timer安排更新會更好。

+0

我不太確定它是否阻止了EDT,因爲它似乎*是在一個單獨的線程(Runnable run方法)中調用的,但是我們從不會看到他是如何啓動線程的,所以很難說如果他那樣做的話。 – 2011-05-06 05:39:40

+0

@Hovercraft充滿鰻魚:你可能是對的,一旦OP發佈了SSCCE,我會給它一些額外的想法。 – 2011-05-06 05:43:52

+0

你是對的! Java讓我的頭受到傷害,我不確定你爲什麼是對的,但是把它改爲Timer可以解決問題。但是,我希望有可變長度的延遲,並且計時器有固定的延遲。有什麼辦法讓它變得可變嗎?現在,我只是將延遲設置得很短,並重復圖像,但我想可能有一個更精美的解決方案。 *編輯:哦,順便說一句,謝謝。 – 2011-05-06 13:35:13

0

您需要執行以下操作:

1)實際上創建一個實例來運行。 2)您需要定期調用repaint()才能重新繪製顯示。

希望它有幫助。乾杯!