ArrayList of Arrays for Interactive Shapes

it seems you have to re-new pos

 if (mousePressed) {
    pos = new int[2];
    pos[0] = mouseX;
    pos[1] = mouseY;

Full code:


int[] pos = new int[2]; // mouseX and mouseY position
ArrayList<int[]> polygon = new ArrayList<int[]>(); // List containing many points with mouseX/mouseY positions

void setup() {
  size(500, 500, P2D);
  background(255);
  strokeWeight(1);
  stroke(1);
  fill(255, 0, 0);
}

void draw() {
  if (mousePressed) {
    pos = new int[2];
    pos[0] = mouseX;
    pos[1] = mouseY;
    // Add current mouseX/mouseY-Array to Array-List
    polygon.add(pos);
  }
}

void mouseReleased() {
  //  polygon.clear();
}

void keyPressed() {
  // Show contents of shape

  for (int i = 0; i < polygon.size(); i++) {
    println("POLYGON "+ i + "   :   " + polygon.get(i)[0], polygon.get(i)[1]);
  }
}
3 Likes