我在Java中,這GUI類:動畫不能正常工作,除非你調整框架
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
public class GUI extends JFrame {
private boolean[][] board;
private int width;
private int height;
private int multiplier = 25;
private int xMarginLeft = 2;
private int xMarginRight = 1;
private int yMarginBottom = 3;
private int yMarginTop = 2;
public GUI(boolean[][] board) {
this.width = GameOfLife.getNextBoard().length + xMarginLeft;
this.height = GameOfLife.getNextBoard()[0].length + yMarginBottom;
setTitle("John Conway's Game of Life");
setSize(width * multiplier, height * multiplier);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
board = GameOfLife.getNextBoard();
g.setColor(Color.black);
g.fillRect(0, 0, width * multiplier, height * multiplier);
g.setColor(Color.green);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j]) {
g.fillRect((i + xMarginRight) * multiplier, (j + yMarginTop) * multiplier, multiplier - 1, multiplier - 1);
}
}
}
}
}
這是從主類的一個片段:
public static void main(String[] args) {
GUI boardGraphics = new GUI(nextBoard);
boolean[][] board = new boolean[nextBoard.length][nextBoard[0].length];
for (int gen = 0; gen < 25; gen++) {
for (int i = 0; i < nextBoard.length; i++) {
for (int j = 0; j < nextBoard[i].length; j++) {
board[i][j] = nextBoard[i][j];
}
}
try {
boardGraphics.paint(null);
}
catch (NullPointerException e) {}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] && !(countSurrounding(board, i, j) == 2 || countSurrounding(board, i, j) == 3)) {
nextBoard[i][j] = false;
}
else if (!board[i][j] && countSurrounding(board, i, j) == 3) {
nextBoard[i][j] = true;
}
}
}
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {}
}
}
然而,當我運行程序,動畫只適用於如果我調整/最小化/最大化框架。這完全是錯誤的動畫方法?或者我的代碼在某些方面不正確?
我看不到板的繪畫在哪裏繼續運行,我只看到一個調用來繪製一個空參數。我會建議你構建從面板擴展的板類,並管理所有刷新,而不是直接通過'JFrame'。 – Noe 2013-05-11 17:35:57
1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)將catch(Exception e){..']形式的代碼更改爲catch(Exception e){e.printStackTrace(); //非常翔實! 3)不要阻塞EDT(Event Dispatch Thread) - 當發生這種情況時,GUI將「凍結」。而不是調用'Thread.sleep(n)'實現一個Swing'Timer'來重複執行任務,或者一個'SwingWorker'執行長時間運行的任務。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 – 2013-05-12 05:44:23