Thursday, June 27, 2019

Object Array returning null values? - Java




I've declared this in Java:



private JToggleButton[] zarObj;



Then on the class constructor filled the array:



this.zarObj = new JToggleButton[]{zar1, zar2, zar3, zar4, zar5};


I need to use zarObj[i] to apply the setIcon method like so in a for loop:



zarObj[i].setIcon(var);



But I'm getting the nullPointerException. And when trying to access the objects:
for (int i=0; i<5; i++) { System.out.println(zarObj[i]); I get 5 null messages in the console.


Answer



You need to initialize those JToggleButtons before calling setIcon() on them:



for (int i=0; i < zarObj.length; i++) {
zarObj[i] = new JToggleButton(params);
zarObj[i].setIcon(var);
}


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...