views:

73

answers:

3

Hello guys. I've been tearing my hair out the past few hours trying to solve this problem. Every time I click on a JButton which should open a JFrame(And it does), i get a stacktrace saying I have a null point exception at these bits of code:

In class A i have:

aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        B instanceofB = new B(userSession.getBalance());
    }
});

and Class B

super.getSomeBtn().setVisible(false);

This is where the stacktrace says the errors are in the two above sections. I have a line exactly the same as the one above in Class B and it works fine?

Really stuck here!

A: 

You could break down those statements to examine each reference one by one for nullness. You can use print/log statements or asserts for this:

assert aButton != null;
aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      assert userSession != null;
      B instanceofB = new B(userSession.getBalance());

        });

...
assert super.getSomeBtn() != null;
super.getSomeBtn().setVisible(false);
Péter Török
+2  A: 

If you use an IDE such as eclipse, set a breakpoint on a NullPointerException. Then when you debug examine the local variables at that point to work out what is null. It seems most likely from this code that getSomeBtn() is returning null which means your B class is not initializing it, or it is calling the wrong superclass constructor. However, there really isn't enough detail/context here to be of any help. When in doubt get the debugger out!

Dean Povey
+1  A: 

Here are 3 points of interest, where NPE can happen:

  • super.getSomeBtn() can be null;
  • userSession can be null
  • some initialization code of class B can throw this exception also, for example such code

    Object _one = null; Object _two = _one.getClass();

during field declaration will cause NPE.

Look through all these three points, I think, you'll find something. Breakpoints/log/asserts — everything will help.

Alexander Babaev