我在小程序中构建一个小游戏。每当我尝试运行它时,我都会收到以下错误
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);
}
}
}
答案 0 :(得分:1)
您必须初始化数组的buttons[i]
元素。 buttons[i] = new ActiveSquare[6]