The below code \"Boxlayout example complies well but throws me the below exception at runtime:
Exception in thread \"main\" java.lang.NullPointerException
at ja
You are shadowing some variables, mainly the JButton variables b1, b2, b3, b4, and b5, by declaring them in the class, and then re-declaring and initializing them in the constructor. The newly declared variables in the constructor are not the same ones that are declared in the class, and so the class variables will remain null.
Solution: don't re-declare the variables in the constructor. So instead of this:
class Foo {
private Bar bar;
public Foo() {
Bar bar = new Bar(); // bar is re-declared here!
}
}
do this:
class Foo {
private Bar bar;
public Foo() {
bar = new Bar(); // notice the difference!
}
}
Also, whenever you have a NullPointerException (NPE) look carefully at the line that throws the exception, here line 26 of the BoxExample class:
at BoxExample.launchFrame(BoxExample.java:26)
You'll find on that line that one of the variables is null. If you find out which variable, you can often backtrack through your code and see why it is null.