easy question (newbie)

M

Michael Cox

MonthComponent[] month = new MonthComponent[12];
month[0].setBackground(Color.WHITE);
"java.lang.NullPointerException"


You've not added anything to the array.
You need to add the months

i.e. month[0] = new MonthComponent();
month[1] = new .....

etc....
 
G

Guest

What is wrong in the following code?
------------
MonthComponent[] month = new MonthComponent[12];
month[0].setBackground(Color.WHITE);
contentPane.add(month[0], BorderLayout.CENTER);
------------

Compiler has no problem but when VM runs 2nd line says:
"java.lang.NullPointerException"

MonthComponent is this code: (nothing for now)
------------
import javax.swing.JComponent;

public class MonthComponent extends JComponent {
public MonthComponent() {
}
}
 
M

Michael Borgwardt

Because I am newbie in Java, I want something like this in C++:
MonthComponent *month = new MonthComponent[12];
month[0].setBackground(Color.WHITE);

The difference is that in C++, the new keyword creates an array of objects.
In Java, it does not, because there *are no* arrays of objects in Java, only
arrays of references, and when the array is created, all references are null.
So you additionally have to create objects and assign references to point
to them.
 
M

Michiel Konstapel

The difference is that in C++, the new keyword creates an array of
objects.
In Java, it does not, because there *are no* arrays of objects in Java,
only
arrays of references, and when the array is created, all references are
null.
So you additionally have to create objects and assign references to point
to them.

Something I've been wondering about... How does this work (in C++) for
classes that have no no-arg constructor? How does it fill the array then?
Michiel
 
C

Carl Howells

Michiel said:
Something I've been wondering about... How does this work (in C++) for
classes that have no no-arg constructor? How does it fill the array then?
Michiel

You have to specify what constructor to use, and what arguments to use.
Every object is constructed using those arguments.
 
M

Michiel Konstapel

Something I've been wondering about... How does this work (in C++) for
You have to specify what constructor to use, and what arguments to use.
Every object is constructed using those arguments.

Well, that certainly makes sense :)
Thanks,
Michiel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top