0

我在 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) {}
    }
}

但是,当我运行程序时,动画只有在我调整/最小化/最大化框架时才有效。这完全是错误的动画方法吗?还是我的代码在某些方面不正确?

4

1 回答 1

1

实际上你是对的:这动画的错误方法:

  1. 您必须在事件调度线程上运行所有访问 GUI 类的代码;
  2. 动画是通过在 Swing 上调度重复任务来实现的Timer,并且从不使用涉及Thread.sleep.
于 2013-05-11T17:25:58.853 回答