Wednesday, 24 May 2017

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...