Sunday 14 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...