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?
You have to initialize each JPanel with something like this::
Array of objects and array of primitive types behave in different ways.
Although elements of array types like
intandfloatare not required to be created on the heap withnew, 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 callnewon each JPanel to initialize them separately.