Omnimaga
General Discussion => Technology and Development => Computer Programming => Topic started by: ElementCoder on January 25, 2013, 03:37:04 pm
-
I have the following arrays:
JTextArea foxBA, foxMA, foxBP, foxMLS;
JTextArea[] textFox = {foxBA, foxMA, foxBP, foxMLS};
String[] label = {"Breeding Age: ", "Max Age: ", "Breeding Probability: ", "Max Litter Size: "};
I initialize them by doing:for(int i = 0; i < textFox.length; i++){
tab2_fox.add(new JLabel(label[i]));
textFox[i] = new JTextArea(1, 5);
textFox[i].setText(Fox.getData().get(i).toString());
tab2_fox.add(textFox[i]);
}
However, when trying to get the text by doingfoxBA.getText()
I get a NullPointerException. But when doing textFox[0].getText()
everything works fine. Why can't I acces the actual object, but can I acces it by using its array reference?
-
This line:
textFox = new JTextArea(1, 5);
is overwriting foxBA, foxMA, foxBP, and foxML in the array, not actually changing the values of them. If you want to be able to access each element of the array by named variables, perhaps set them equal to their appropriate array elements after the array has been initialized?
-
I see. Any suggestions on how to make it change the value?
-
It's not possible to change the values of foxBA, foxMA, foxBP, and foxMLS through the array. Those four variables do not point to elements of the array, nor do the elements of the array point to the variables.
I think the least changes you could perform to make this work would be to change the array initializations to this:
JTextArea[] textFox = new JTextArea[4];
String[] label = {"Breeding Age: ", "Max Age: ", "Breeding Probability: ", "Max Litter Size: "};
Then perform your initialization code, and then initialize the individual variables:
JTextArea foxBA = textFox[0], foxMA = textFox[1], foxBP = textFox[2], foxMLS = textFox[3];
My object-oriented design teacher would probably yell at any student who used code like this in general, but that's a different matter. :P