除非您调整框架大小,否则动画无效

时间:2013-05-11 17:19:34

标签: java user-interface

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

但是,当我运行程序时,只有在我调整/最小化/最大化帧时,动画才有效。这完全是错误的动画方法吗?或者我的代码在某种程度上是不正确的?

1 个答案:

答案 0 :(得分:1)

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

  1. 您必须运行在Event Dispatch Thread上访问GUI类的所有代码;
  2. 动画是通过在Swing的Timer上安排重复任务来实现的,并且从不使用涉及Thread.sleep的循环。
相关问题