This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


4年前关闭。




我正在用小程序构建一个小游戏。每当我尝试运行它时,我都会在网上收到以下错误
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);
        }
    }
}

最佳答案

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

10-07 16:51