I am trying to assign text to buttons inside a loop but I am getting an NullPointerException.
I have initialized the button array inside constructor of the class and after initilizatoin, I call the following method. Here is the code where I am getting error.
public class Alfred
{
private String names[]={"nfs","gta","maxpayne","hitman"};
private JButton but[];
public Alfred()
{
...
but= new JButton[4];
AssignLettersToButtons();
}
private void AssignLettersToButtons()
{
for(int i=0;i<names.length;i++)
{
but[i].setText(names[i]); // error
pane1.add(but[i]);
}
}
}
}
The length of button array and names array is same. What is the reason for this exception and how can I solve it?
Regards
This only allocates space for four array elements; each element is initialized to
null, the default value for a reference type like yourJButtonobjects.but[0],but[1],but[2],but[3]are allnull.You should initialize them like this: