有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

除非调整帧的大小,否则java动画不起作用

我有一个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) 个答案

  1. # 1 楼答案

    实际上你是对的:这是一种错误的动画制作方法:

    1. 必须在事件分派线程上运行访问GUI类的所有代码
    2. 动画是通过在Swing的Timer上安排一个重复的任务来实现的,并且从不使用涉及Thread.sleep的循环