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显示下一代康威游戏时,我得到了一个nullpointer异常。请建议我的代码有什么问题。单击开始按钮时执行动作执行方法
答案 0 :(得分:2)
NullPointerException的原因是:
grid = new JButton[length+20][width+20];
grid1 = new JButton[length+20][width+20];
这样,您有一个JButtons
的二维数组,但它仍然充满null
个值。您必须初始化数组中的单个“单元格”:
for (int i = 0; i < length+20; i++) {
for(int j = 0; j < width+20; j++) {
grid1[i][j] = new JButton();
}
}
此外,数组的大小是否有意,或者应该是length+2
x width+2
,而不是像for循环一样?
但这不是你的实际问题:你创建一个新的按钮数组,然后检查那些新创建的按钮的背景颜色。假设grid
表示游戏的当前状态,您在进行更新之前擦除游戏状态。更有可能的是,你必须完全放弃grid = new JButton[length+20][width+20];
行。
即使这样也无法正常工作,因为两个数组grid
和grid1
会保持相同的按钮,因此当您更改其中一个的背景颜色时,还可以更改备份中的背景颜色。使用grid1[i][j]=grid[i][j]
,您只需将按钮的引用复制到另一个数组,但不要创建新按钮。即使你这样做了,你也会遇到根本不在GUI中的新按钮的问题。
不是将游戏状态存储在GUI元素中,而是应该使用两个布尔二维数组(一个用于当前状态,一个用作状态更新期间先前状态的备份)并设置背景颜色。基于那些布尔值的按钮。