So I have a class dealing with buttons and I have an array of rectangles containing 2 individual rectangular shapes. Now when I make a variable which retrieves say the 0th index of the array it will give me a nullpointerexception I have been scratching my head over this I have clearly declared and initialised the array and made it the appropriate size for 2 rectangles to be contained and have assigned these to the indexes. I must be missing something really small which I can't seem to figure out.
Below I have put the relevant code for this:
public class MenuButton {
private int height;
private int width;
private float positionX;
private float positionY;
//private ArrayList<Rectangle> rects;
private Rectangle rects[];
private Rectangle play;
private Rectangle touchToPlay;
private boolean isTouched;
public MenuButton(int height, int width, float positionX, float positionY){
this.height = height;
this.width = width;
this.positionX = positionX;
this.positionY = positionY;
isTouched = false;
Rectangle rects[] = new Rectangle[2];
play = new Rectangle(positionX, positionY, width, height);
touchToPlay = new Rectangle(positionX, positionY, width, height);
//can clean this up by introducing initButtons() to assign buttons to
//indexes of the array
rects[0] = play;
rects[1] = touchToPlay;
}
public boolean isClicked(int index,float screenX, float screenY){
//ERROR IS BELOW THIS LINE
Rectangle rect = rects[0];
return rect.contains(screenX, screenY);
}
Youre shadowing the variable rects. Replace
Rectangle rects[] = new Rectangle[2];
with
rects = new Rectangle[2];
Yes, the rects variable is local to the MenuButton constructor (I assume it's a constructor). This means it is hiding the field you declared in the class with the same name. So you initialized the local variable, then at the end of the constructor, it was gone. The field remained empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With