gpt4 book ai didi

java - 将 conways 代码与 gui 结合起来

转载 作者:行者123 更新时间:2023-12-02 06:36:35 24 4
gpt4 key购买 nike

    public void actionPerformed(ActionEvent e){
grid=new JButton[length+20][width+20];
grid1=new JButton[length+20][width+20];

for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid1[i][j]=grid[i][j];
}
}


for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
//final int row = i;
//final int col = j;

int count=0;

if(grid[i][j-1].getBackground() == Color.BLACK);
count++;

if(grid[i][j+1].getBackground()==Color.BLACK)
count++;

if(grid[i-1][j-1].getBackground()==Color.BLACK)
count++;

if(grid[i-1][j].getBackground()==Color.BLACK)
count++;

if(grid[i-1][j+1].getBackground()==Color.BLACK)
count++;

if(grid[i+1][j-1].getBackground()==Color.BLACK)
count++;

if(grid[i+1][j].getBackground()==Color.BLACK)
count++;


if(grid[i+1][j+1].getBackground()==Color.BLACK)
count++;

if(count==3) // exactly three neighbors
{

if(grid[i][j].getBackground()==Color.WHITE)
{
grid1[i][j].setBackground(Color.BLACK); // birth cell
}
}

if(count==2 || count==3) // 2 or 3 neighbors
{

if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.BLACK); // survives
}
}

if(count>=4 || count<=1) //4 or more neighbors, or 1 or less neighbor
{
if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.WHITE); // dies from over-population or isolation
}
}
}
}

for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid[i][j]=grid1[i][j];
}
}

for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
System.out.print(grid[i][j]);
}
System.out.println("\n");
}
}

当我尝试使用 GUI 显示下一代康威生命游戏时,出现空指针异常。请建议我的代码有什么问题。单击开始按钮时执行操作执行方法

最佳答案

NullPointerException的原因是这样的:

grid  = new JButton[length+20][width+20];
grid1 = new JButton[length+20][width+20];

这样,你就有了一个 JButtons 的二维数组,但仍然充满了null值(value)观。您必须初始化数组中的各个“单元”:

for (int i = 0; i < length+20; i++) {
for(int j = 0; j < width+20; j++) {
grid1[i][j] = new JButton();
}
}

此外,数组的大小是故意的,还是应该是 length+2 xwidth+2相反,就像在 for 循环中那样?

但这不是您的实际问题:您创建一个新的按钮数组,然后检查这些新创建的按钮的背景颜色。假设grid代表游戏的当前状态,您在更新之前删除游戏状态。更有可能的是,您必须挂断电话 grid = new JButton[length+20][width+20];完全。

即使这样也无法正常工作,因为两个数组 gridgrid1将保留相同按钮,因此当您更改其中一个按钮的背景颜色时,您也会更改备份中的背景颜色。与grid1[i][j]=grid[i][j]您只需将对按钮的引用复制到另一个数组,但不创建新按钮。即使您这样做了,您也会遇到新按钮根本不会出现在 GUI 中的问题。

您不应该将游戏状态存储在 GUI 元素中,而应该使用两个 2D boolean 数组(一个用于当前状态,一个作为状态更新期间前一个状态的备份)并设置游戏的背景颜色基于这些 boolean 值的按钮。

关于java - 将 conways 代码与 gui 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19580724/

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