-1

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:

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

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

What am I doing wrong? :/

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Wartogh
  • 1
  • 2

2 Answers2

1

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

  • even if addCube was null ... as long as you're not actually trying to call one of it's (instance) members, I doubt it would thrown an NPE – Stultuske Jan 21 '16 at 10:03
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! :)

Wartogh
  • 1
  • 2