所以我有一个处理按钮的类,我有一个包含2个单独矩形的矩形数组。现在,当我创建一个检索数据的第0个索引的变量时,它会给我一个nullpointerexception,我一直在摸着头,我已经清楚地声明并初始化了数组并使其成为2个矩形的适当大小。已将这些分配给索引。我必须遗漏一些我似乎无法弄清楚的小东西。
下面我已经为此提供了相关代码:
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);
}
答案 0 :(得分:7)
答案 1 :(得分:1)
是的,rects
变量是MenuButton
构造函数的本地变量(我假设它是构造函数)。这意味着它隐藏了您在类中声明的具有相同名称的字段。所以你初始化了局部变量,然后在构造函数的末尾,它就消失了。该领域仍然是空的。
答案 2 :(得分:1)
您已宣布Rectangle rects[]
两次。只需将构造函数中的行更改为rects = new Rectangle[2];