在Java中使用对象的ArrayList(处理)

时间:2015-02-17 20:29:25

标签: java arraylist 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。为什么会这样?

1 个答案:

答案 0 :(得分:6)

我相信

x = x;
y = y;

应该是

this.x = x;
this.y = y;
在你的Piece()构造函数中

。 x = x只是将值设置为自身,使用this关键字将根据您尝试传入的值设置Piece的值。