Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nullpointerexception when retrieving a rectangle from the array of rectangles

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);
} 
like image 686
Jesal Patel Avatar asked Jan 29 '26 21:01

Jesal Patel


2 Answers

Youre shadowing the variable rects. Replace

Rectangle rects[] = new Rectangle[2];

with

rects = new Rectangle[2];
like image 130
Reimeus Avatar answered Feb 01 '26 09:02

Reimeus


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.

like image 32
RealSkeptic Avatar answered Feb 01 '26 10:02

RealSkeptic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!