0

I'm trying to make an array of jpanels but I got some null pointer exception.

here is the part of the code. The cartP here is a panel.

JPanel[] p2 = new JPanel[10];
    p2[0].setPreferredSize(new Dimension(700, 40));
    p2[0].setMaximumSize(p2[0].getPreferredSize());
    p2[0].setLayout(new GridLayout(1,5,1,1));
    p2[0].add(new JLabel("text"));
    p2[0].add(new JLabel("text"));
    p2[0].add(new JLabel("text"));
    p2[0].add(new JLabel("text"));
    p2[0].setBackground(Color.CYAN);

    cartP.add(p2[0]);

I'll use it for making a view cart just like on the shopping website.

here is the exception..

Exception in thread "main" java.lang.NullPointerException
at storeapp.Cart.gui(Cart.java:59)
at storeapp.Cart.<init>(Cart.java:29)
at storeapp.Cart.main(Cart.java:157)

Java Result: 1

Any idea why i get that exception?

3 Answers 3

3

Because

JPanel[] p2 = new JPanel[10];

creates an array of null JPanel pointers. You need to initialize each element of the array before using it.

for (int i=0; i<p2.length; i++) {
    p2[i] = new JPanel(/* snip */);
}

This is consistent with the behavior for any array initialization. Until otherwise assigned, elements of an array have the array type's default value; for any object type, the default value is null.

1

You have to initialize each JPanel with something like this::

for(int i = 0; i < 10; i++){
   p2[i] = new JPanel();
}

Array of objects and array of primitive types behave in different ways.

Although elements of array types like int and float are not required to be created on the heap with new, you must initialize arrays of objects.

JPanel[] panels = new JPanel[10] creates 10 UNINITIALIZED objects for JPanel(or just initializes the array). Since they're not initialized, you will have to call new on each JPanel to initialize them separately.

1
  • "...creates 10 UNINITIALIZED objects" is a misleading sentence. There is no such thing as an "uninitialized object," only variables and references which have not been initialized. It is also misleading/incorrect to say "call new on [a] JPanel." You are not calling a method, nor applying an operator to, an existing object. Commented Oct 21, 2012 at 22:49
1
JPanel[] p2 = new JPanel[10];

for (int i = 0; i < p2.length; i++){
    p2[i] = new JPanel();
}

....

your code

1
  • You can add some information also. Why and where to do those changes? Commented Oct 21, 2012 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.