尝试使用JButton时出现NullPointerException

时间:2022-08-11 21:22:09

This is the code:

这是代码:

    addCube = new JButton("Add Cube");
    addCube.addKeyListener(kl);
    addCube.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            cubes.add(cube);
        }
    });
    panel.add(addCube);
    frame.add(panel, BorderLayout.NORTH);

Where panel is an JPanel and frame is an JFrame. When I execute the code I got the following error message:

其中panel是JPanel,frame是JFrame。当我执行代码时,我收到以下错误消息:

Exception in thread "main" java.lang.NullPointerException at cg2k15.CG2K15.main(CG2K15.java:91)

cg2k15.CG2K15.main(CG2K15.java:91)中线程“main”java.lang.NullPointerException中的异常

Where line 91 is this: panel.add(addCube);

第91行是这样的:panel.add(addCube);

What am I doing wrong? :/

我究竟做错了什么? :/

2 个解决方案

#1


1  

Your addCube object is clearly not null since it has already been initialized, looks like you forgot to initialize your panel.

你的addCube对象显然不是null,因为它已经被初始化,看起来你忘了初始化你的面板。

#2


0  

Thanks guys. It ended up that the problem was that I was doing everything directly under the main method. I read that a constructor shouldn't initialize a static field. The buttons should be private instance fields of the frame and the main method shouldn't deal with them. After I created another class just to deal with the frame, it solved the problem! :)

多谢你们。最后问题是我在主方法下直接做了一切。我读到构造函数不应该初始化静态字段。按钮应该是框架的私有实例字段,主方法不应该处理它们。在我创建另一个类来处理框架后,它解决了问题! :)

#1


1  

Your addCube object is clearly not null since it has already been initialized, looks like you forgot to initialize your panel.

你的addCube对象显然不是null,因为它已经被初始化,看起来你忘了初始化你的面板。

#2


0  

Thanks guys. It ended up that the problem was that I was doing everything directly under the main method. I read that a constructor shouldn't initialize a static field. The buttons should be private instance fields of the frame and the main method shouldn't deal with them. After I created another class just to deal with the frame, it solved the problem! :)

多谢你们。最后问题是我在主方法下直接做了一切。我读到构造函数不应该初始化静态字段。按钮应该是框架的私有实例字段,主方法不应该处理它们。在我创建另一个类来处理框架后,它解决了问题! :)