Home

Arrays

Example: Horizontal grid

color[] colors = new color[10];

void setup()
{
  size(900, 100);
  for(int i = 0; i < colors.length; i++)
  {
    colors[i] = color(random(0, 255), random(0, 255), random(0, 255));
  }
  noStroke();
}

void draw()
{
  background(0);
  for(int i = 0; i < colors.length; i++)
  {
    int w = width / colors.length;
    int h = 100;
    int x = i * w;
    int y = 0;
    fill(colors[i]);
    rect(x, y, w, h);
  }
}

void mouseClicked()
{
  // suppose the mouse click was at mouseX=427
  int boxId = mouseX / (width / colors.length);
  colors[boxId] = color(random(0, 255), random(0, 255), random(0, 255));
}

void keyPressed()
{
  int boxId = key - 48;
  if(boxId >= 0 && boxId < colors.length)
  {
    colors[boxId] = color(random(0, 255), random(0, 255), random(0, 255));
  }
}

CSCI 111 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.