问题描述
- 一个程序里面出现了nopointerexception,但是我觉得没有空变量啊
-
import javax.swing.*;
import java.awt.*;
public class ex123{
public static void main(String args[]){
wingrid win =new wingrid();
}
}
class wingrid extends JFrame{
GridLayout grid;
JPanel chessboard;
wingrid(){chessboard=new JPanel();
grid=new GridLayout(12,12);
chessboard.setLayout(grid);
JLabel[][] label=new JLabel[12][12];
for(int i=0;i<12;i++){
for(int j=0;j<12;j++){
label[i][j]=new JLabel();
if((i+j)%2==0)
label[i][j].setBackground(Color.black);
else
label[i][i].setBackground(Color.white);
chessboard.add(label[i][j]);
}
}
add(chessboard,BorderLayout.CENTER);
add(new Button("北方参战者"),BorderLayout.NORTH);
add(new Button("南方参战者"),BorderLayout.SOUTH);
add(new Button("西方参战者"),BorderLayout.WEST);
add(new Button("东方参战者"),BorderLayout.EAST);
setBounds(10,10,570,390);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
}
解决方案
import javax.swing.*;
import java.awt.*;
public class aa {
public static void main(String args[]) {
wingrid win = new wingrid();
}
}
class wingrid extends JFrame {
GridLayout grid;
JPanel chessboard;
wingrid() {
chessboard = new JPanel();
grid = new GridLayout(12, 12);
chessboard.setLayout(grid);
JLabel[][] label = new JLabel[12][12];
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if ((i + j) % 2 == 0)
{
label[i][j] = new JLabel();
label[i][j].setBackground(Color.black);
chessboard.add(label[i][j]);
}
else
{
label[i][i] = new JLabel();
label[i][i].setBackground(Color.white);
chessboard.add(label[i][i]);
}
}
}
add(chessboard, BorderLayout.CENTER);
add(new Button("北方参战者"), BorderLayout.NORTH);
add(new Button("南方参战者"), BorderLayout.SOUTH);
add(new Button("西方参战者"), BorderLayout.WEST);
add(new Button("东方参战者"), BorderLayout.EAST);
setBounds(10, 10, 570, 390);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
}
这样就可以了,没有初始化label[i][i] = new JLabel();
解决方案二:
看下异常报错指向哪一行呢?就坚持这行所有对象的.操作,排查是否为空。工具是不会有错的,还是仔细排查下吧。要不就是你修正后没有重新编译。
解决方案三:
能运行就可以了,,效果没出来那是你自己的逻辑问题