使用 Java 中对象的 ArrayList(处理中)
Using an ArrayList of objects in Java (Processing)
我在 Processing (Java) 中创建了以下草图:
ArrayList<Piece> pieces = new ArrayList<Piece>();
void setup() {
size(300, 300);
pieces.add(new Piece(100, 200)); // I ADD ONE PIECE TO THE ARRAY LIST
}
void draw() {
background(0);
for (int i = 0; i < pieces.size(); i++) {
Piece p = pieces.get(i);
p.display(); // I WANT TO DRAW THE PIECE I'VE CREATED IN SETUP()
}
}
class Piece {
int x;
int y;
Piece (int x, int y) {
x = x;
y = y;
}
void display() {
fill(255);
ellipse(x, y, 30, 30); // AS X IS 100 AND Y IS 200, A BALL SHOULD BE DRAWN AT THOSE COORDINATES, BUT INSTEAD THE BALL IS DRAWN AT 0,0. WHY THAT?
}
}
我向坐标为 (100,200) 的数组列表中添加了一件。当我执行 p.display() 时,它会在 0,0 而不是 100,200 处绘制椭圆。为什么会这样?
我相信
x = x;
y = y;
应该是
this.x = x;
this.y = y;
在您的 Piece() 构造函数中。 x=x 只是将值设置为自身,使用 this
关键字将根据您尝试传入的值设置您的 Piece 的值。
我在 Processing (Java) 中创建了以下草图:
ArrayList<Piece> pieces = new ArrayList<Piece>();
void setup() {
size(300, 300);
pieces.add(new Piece(100, 200)); // I ADD ONE PIECE TO THE ARRAY LIST
}
void draw() {
background(0);
for (int i = 0; i < pieces.size(); i++) {
Piece p = pieces.get(i);
p.display(); // I WANT TO DRAW THE PIECE I'VE CREATED IN SETUP()
}
}
class Piece {
int x;
int y;
Piece (int x, int y) {
x = x;
y = y;
}
void display() {
fill(255);
ellipse(x, y, 30, 30); // AS X IS 100 AND Y IS 200, A BALL SHOULD BE DRAWN AT THOSE COORDINATES, BUT INSTEAD THE BALL IS DRAWN AT 0,0. WHY THAT?
}
}
我向坐标为 (100,200) 的数组列表中添加了一件。当我执行 p.display() 时,它会在 0,0 而不是 100,200 处绘制椭圆。为什么会这样?
我相信
x = x;
y = y;
应该是
this.x = x;
this.y = y;
在您的 Piece() 构造函数中。 x=x 只是将值设置为自身,使用 this
关键字将根据您尝试传入的值设置您的 Piece 的值。