Arranging an array of objects in a grid

This below renders permanent color change to button when mouseOver and mousePressed.

QUESTION #1Though am trying – without success – to get a new random color each time with each mousePressed on same button. As code currently runs I can change each button color only one time. I would like to be able to change the button color more than once.

Do I need to create an additional function to generate new random colors and integrate that new function into the mousePressed function?

QUESTION #2 – And then additionally, one step further, if I want ALL of the buttons to change color randomly, with a mousePressed, would that require setting up another counter to iterate through the number of buttons?

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

color bgColor = color (random(255), random(255), random(255));
color color2; // new random color for mouseOver each time mouse is pressed 

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

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

  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
        color2, // new random color when mousePressed 
        random(50, 125)); // random sizes
      k++;
    }
  }
}
void draw() {

  background (bgColor);
  //color2 = color (random(255), random(255), random(255));
  /*for (int i = 0; i < many; i++) 
   myButtons[i].mouseOver();*/

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

void mousePressed() { 

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

  if (mousePressed) {
    color2 = color (random(255), random(255), random(255));

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

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

class Button {
  float x, y;
  color color1;
  color 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() {
    if (off) {
      fill (color1);
      noStroke();
    } else {
      fill (color2);
      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;
    }
  }
}
1 Like