我正在用Java編寫一個簡單的Game of Life程序,並且讓它動起來有點麻煩。我有一個的JComponent類稱爲LifeDraw,顯示像素的網格,具有以下paint方法:使用Java的JComponent repaint()
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int y = 0; y < lGrid.getHeight(); y++) {
for (int x = 0; x < lGrid.getWidth(); x++) {
if (lGrid.getCell(x,y) == 1) {
g.setColor(Color.red);
g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
} else {
g.setColor(Color.white);
g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
}
}
}
}
然後另一個類LifeGrid,有一個方法run()
,其調用時將更新一代像素的網格,然後致電LifeDraw.repaint()
。但是,如果我嘗試在循環中調用run()
,那麼在循環完成之前,不會重新繪製,因此所有顯示的內容都是第一代和最後一個。我想它可能只是更新太快而無法重新繪製,所以我嘗試在迭代之間使用Thread.sleep()
,但仍然存在相同的問題。理論上(或者至少我希望是這樣),它應該在每次迭代之間重新繪製組件,並顯示像素變化的動畫。
我不太熟悉Java GUI,所以任何幫助都會非常感激。希望我已經足夠清楚地解釋了,否則讓我知道!
可能與此處的問題相同:http://stackoverflow.com/questions/1843677/why-does-invokelater-cause-my-jframe-not-to-display-correctly – 2010-01-06 21:24:08