Arranging an array of objects in a grid

first only a reformat and change to have 2 colors set

int gridX = 5, gridY = 5, many = gridX*gridY; // cells per row and column, # in total
Button [] myButtons = new Button [many]; // declaring Button class array

color bgColor = color (random(255), random(255), random(255));

void setup() {
  size (600, 600);
  setup_myButtons();
}

void setup_myButtons() {
  int x = 40 + 50, y = x, // dist from screen border
    w = 100, h = w, off = 5; // width and height of one cell, dist between cells
  int k = 0; // counter for button objects in array
  for (int i = 0; i < gridX; i++) { // counter for xpos on grid
    for (int i2 = 0; i2 < gridY; i2++) { // counter for ypos on grid
      myButtons [k] = new Button ( x + i * (w+off), y + i2 * (h+off), 
        color (random(255), random(255), random(255)), // random colors
        color (random(255), random(255), random(255)), // new random color when mousePressed 
        random(50, 125)); // random sizes
      k++;
    }
  }
}

void draw() {
  background (bgColor);
  for (int i = 0; i < many; i++)  myButtons[i].display();
}

void mousePressed() { 
  // bgColor = color(random(255), random(255), random(255));
  for (int i = 0; i < many; i++) myButtons[i].mouseOver();  // set ON OFF fill color select
}

//
class Button {
  float x, y;
  color color1,color2;
  float sz;
  boolean off = true; // button starts in OFF position

  Button ( float tempX, float tempY, color tempColor1, color tempColor2, float tempSz) {
    x = tempX;
    y = tempY;
    color1 = tempColor1;
    color2 = tempColor2;
    sz = tempSz;
  }

  void display() {
    noStroke();
    if (off)     fill (color1);
    else         fill (color2);
    rectMode(CENTER);
    rect(x, y, sz, sz);
  }

  void mouseOver() {
    if (mouseX > x - sz/2  &&  mouseX < x + sz/2  &&
      mouseY > y - sz/2  &&  mouseY < y + sz/2  ) off = ! off; // toggle
  }
}


now for further change ( operation example keyboard )
to set class memory variable color2

generally there are 2 ways,
?bad? just write:

void keyPressed() {
  if ( key == 's' )  for (int i = 0; i < many; i++) myButtons[i].color2 = color(random(255), random(255), random(255)); // see only if off == false
}

?good?


  void set_new_random_color2() {
    color2 = color(random(255), random(255), random(255));
  }
  
} // end class

void keyPressed() { //______________________________ OPERATION
  if ( key == 's' )  for (int i = 0; i < many; i++) myButtons[i].set_new_random_color2(); // see only if off == false
}

2 Likes