2015-11-01 66 views
0

我正在一个小程序中构建一个小游戏。每当我尝试运行它,我得到就行了以下错误 buttons[i][k] = new ActiveSquare(k); 填充二维数组时出现空指针异常

错误:

java.lang.NullPointerException 
at com.proj3.renee.ClickAid.<init>(ClickAid.java:21) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:526) 
at java.lang.Class.newInstance(Class.java:379) 
at sun.applet.AppletPanel.createApplet(AppletPanel.java:795) 
at sun.applet.AppletPanel.runLoader(AppletPanel.java:724) 
at sun.applet.AppletPanel.run(AppletPanel.java:380) 
at java.lang.Thread.run(Thread.java:745) 

我类似的答案,newInstance0发出读了,我已经检查,以确保ActiveSquare内的类正在工作,但我仍然不能解决问题。任何建议或进一步阅读将不胜感激。 这里的代码和构造函数的第一位(我可以发布更多,如果需要):

public class ClickAid extends Applet implements ActionListener { 
ActiveSquare[][] buttons; 
private static final long serialVersionUID = 1L; 

public ClickAid() { 
    setLayout(new GridLayout(0, 2, 5, 5)); 
    JPanel panel = new JPanel(); 
    add(panel); 

    for (int i = 0; i < 4; ++i){//default = 4 
      for (int k = 0; k < 6; ++k){ 
        buttons[i][k] = new ActiveSquare(k); //this is where the error is 
        panel.add(buttons[i][k].buttonaspect); 
        buttons[i][k].buttonaspect.addActionListener(this); 
     } 
    }  
} 
+2

看起来你只是想'ActiveSquare [] []按钮=新的ActiveSquare [4] [6];' –

回答

1

你必须初始化数组的元素buttons[i]buttons[i] = new ActiveSquare[6]