gpt4 book ai didi

java - 除非调整框架大小,否则动画无法正常工作

转载 作者:行者123 更新时间:2023-12-01 14:35:47 24 4
gpt4 key购买 nike

我在 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. 您必须在事件调度线程上运行访问 GUI 类的所有代码;
  2. 动画是通过在 Swing 的 Timer 上调度重复任务来实现的,并且从不使用涉及 Thread.sleep 的循环。

关于java - 除非调整框架大小,否则动画无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com