Domanda

I have a JComponent reference like JComponent allComp[]; Now I want to every element of this array holds different type of component like below,

allComp[0] = new JComboBox();

allComp[1] = new JButton();

allComp[2] = new JMonthChooser();

I am trying and getting Null Pointer exception. Is this possible?? If possible how?? Please help me in this issue. Thanks advance

È stato utile?

Soluzione

You probably have not initialized allComp and it's null.

JComponent allComp[] = new JComponent[MAX_COMPONENTS];

Anyway, it is advisable to use a List instead of an array if you don't know beforehand the number of components.

List<JComponent> allComp = new ArrayList<>();
allComp.add(new JComboBox());
allComp.add(new JButton());
allComp.add(new JMonthChooser());

Altri suggerimenti

You need to create the array object itself:

JComponent[] allComp = new JComponent[ARRAYSIZE]; 

I assume that you haven't initialized the array

int arraySize = 20;
JComponent allComp[] = new JComponent[arraySize];

Doing something like

JComponent allComp[]

Only "declares" the object, which is sort of like a promise "somewhere in this code I will use this object, but I haven't decided what I want it to be yet, so I'm leaving it undefined".

"Initialization" is what you need to do to actually create the object. Usually you do this with the

new

keyword.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top