Arranging an array of objects in a grid

I had wondered about the w and h…
But have now deleted in the class to no ill effect.

And have added a mouse over effect function in the class, replacing the click function. A nicer interaction than clicking!

So it now looks like this:
/////////////////////////////////////////////////

int gridX = 5; 
int gridY = 5;
int many = gridX*gridY; // cells per row and column, # in total

Button [] myButtons = new Button [many]; // declaring Button class array

int r = int(random(255));
int g = int(random(255));
int b = int(random(255));

color background = color ( r, g, b) ; 

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

  int x = 40 + 50, y = x, // dist from screen border
    w = 100, h = w, off = 5; // width and height of one cell, dist btwn 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 colors when on / off toggle 
        random(50, 125)); // random sizes
      k++;
    }
  }
}
void draw() {

  background (background);

  for (int i = 0; i < many; i++) 
    myButtons[i].mouseOver();

  for (int i = 0; i < many; i++) 
    myButtons[i].display();
}

void mouseClicked() { 

  background = color(random(255), random(255), random(255));
}

/////////////////////////////////////

class Button {
  float x, y;
  color colRect;
  color colRect2;

  float sz;
  boolean off = true; // button starts in OFF position

  Button ( 
    float tempX, float tempY, 
    color tempColor, color tempColor2, float tempSz) {

    x = tempX;
    y = tempY;

    colRect = tempColor;
    colRect2 = tempColor2;

    sz = tempSz;
  }

  void display() {
    if (off) {
      fill (colRect);
      noStroke();
    } else {
      fill (colRect2);
      noStroke();
    }

    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 = false;
    } else {
      off = true;
    }
  }
}

Thank you @Chrisir for your guidance on this! :grin:

2 Likes