Error writing to an array with the static modifier.
I have an array of intergers that I write data to in a for loop, they have the static modifier, so I can refer to them in another method in another class, I don't really know what the static modifier does :o , I just put it on because eclipse said I would be unable to refer to the array otherwise. I have an array another object as well, with the same lengt, and data is written to it in the same for loop, the only difference is that it doesn't have the static modifier. Oh yes by the way, the error that I'm getting is an array out of bounds exception
The code looks like this.
Code Java:
import java.awt.Graphics;
public class Menu{
public Sprite sprite;
public Util.GuiButton button[];
String file;
int number;
double x, y;
private static int buttonX;
//this static array causes the problem
private static int buttonY[];
public Menu(int number, String file, double x, double y){
//file which contains the images for the buttons
this.file = file;
//number of buttons
this.number = number;
//x and y position of background image for menu
this.x = (int)x;
this.y = (int)y;
//the array of buttons.
button = new GuiButton [number];
//the intializer for the static array that causes the problem
buttonY = new int[number];
}
//draws the graphics
public void draw(Graphics g){
//draws background image.
this.sprite = ImageLoader.get().getSprite(file + "\\menu.png");
int width = sprite.getWidth();
sprite.Draw(g,(int) x,(int) y);
for(int i = 0; i < number; i++){
//draws buttons equally on the screen.
this.button[i] = ImageLoader.get().getGuiButton(file + "\\button" + i + ".png");
double remainingSpace = 541- ((number - 1)*(520/number));
button[i].Draw(g, ((int)x +width/2) - (button[i].getWidth()/4), ((i*(541/number)) + ((int)remainingSpace / 2)) - button[i].getHeight());
//creates variables for the x and y position of the button, so I can test to see if they were clicked in a mouseListener
buttonX = ((int)x +width/2) - (button[i].getWidth()/4);
//the line that eclipse says the error is on when the code is run
buttonY[i] = ((i*(541/number)) + ((int)remainingSpace / 2)) - button[i].getHeight();
}
}
Re: Error writing to an array with the static modifier.
PS, I tried running without the static modifier and IT WORKED PERFECTLY, unfortunately the variable is then useless to me because I can't refer to it in my method.
Re: Error writing to an array with the static modifier.
I've worked out what was wrong, the array inilalizer was not static, but for some reason it did not put an error when the array was declared, it just created an array with the length of zero. Sorry to waste people's time, MERRY CHRISTMAS