我正在将数组更改为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);
}
}
您可能会在此处隐藏textlines变量:
ArrayList textlines = new ArrayList();
因为你在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();
}
要解决这个问题:
ArrayList textlines;
void setup() {
// ...
// *** now it does
textlines = new ArrayList();
}
我可以看到上面的代码有3个问题:你试图两次声明相同的东西,没有声明变量/对象(通常在左箭头和右箭头之间声明),并且你的ArrayList没有数字,那些是你的问题。
您有两个空格可以声明ArrayList:
空间1:
ArrayList textLines = new ArrayList();
void setup() {
//Code goes in here.
}
空间2:
ArrayList textLines;
void setup() {
//other code goes here.
textLines = new ArrayList();
}