ArrayList错误"NullPointerException"

Dou*_*uga 1 java processing nullpointerexception

我正在将数组更改为arrayList,有几个试验有错误"NullPointerException",代码简化如下所示,当mousePressed创建一个矩形.但仍然有同样的错误.问题是什么?

ArrayList textlines;

int xpos=20;
int ypos=20;

void setup() {
  size(1200, 768);
  ArrayList textlines = new ArrayList();
  //(Line)textlines.get(0) =textlines.add(new Line(xpos, ypos));
}

void draw() {
}


void mousePressed() {
  textlines.add(new Line(xpos, ypos));
  for (int i=0; i<textlines.size(); i++) {

    Line p=(Line)textlines.get(i);
    p.display();
  }
}


class Line {

  int x;
  int y;

  Line(int xpo, int ypo) {
    x =xpo;
    y =ypo;
  }

  void display() {
    fill(50, 50, 50);
    rect(x, y, 5, 5);
  }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

您可能会在此处隐藏textlines变量:

ArrayList textlines = new ArrayList();
Run Code Online (Sandbox Code Playgroud)

因为你在方法中重新声明了它setup().不要那样做.在课堂上宣布一次.

具体来说,检查评论:

ArrayList textlines;

void setup() {
  // ...

  // *** this does not initialize the textlines class field
  // *** but instead initializes only a variable local to this method.
  ArrayList textlines = new ArrayList();

}
Run Code Online (Sandbox Code Playgroud)

要解决这个问题:

ArrayList textlines;

void setup() {
  // ...

  // *** now it does
  textlines = new ArrayList();

}
Run Code Online (Sandbox Code Playgroud)