in this version
int num = 10,cols = num, rows = cols; // Number of columns and rows in the grid
Button [][] myButtons= new Button[cols][rows]; // 2D Grid Array of Button objects
color background = color (random(255), random(255), random(255));
void setup() {
size(500, 500);
int x = (width/num)/2, y = x;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
// Initialize each object
myButtons[i][j] = new Button (x+ i*(width/cols), y+ j*(height/rows),
color (random(255), random(255), random(255)), // random colors
color (random(255), random(255), random(255)), // new random colors when mouseOver
(width/num));
}
}
}
void draw() {
background(background);
for (int i = 0; i < cols; i++)
for (int j = 0; j < rows; j++)
myButtons[i][j].display();
}
void keyReleased() {
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
myButtons[i][j].keyPressed();
}
}
}
//////////////////////////////
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() {
mouseOver();
if (off) fill (colRect);
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;
}
void keyPressed() {
if ( ! off ) {
if (keyCode== UP) y -= 1;
else if (keyCode== DOWN) y += 1;
else if (keyCode== LEFT) x -= 1;
else if (keyCode== RIGHT) x += 1;
}
}
}
the mouse position selects a rectangle
and the keyboard operation does move only that on rectangle
( it was not clear if that is the operation concept you wanted to test )
it is not a very good concept as when the rect moves it will go outside the mouse position and stop moving…
possibly change to mouse click selects one rectangle ( might need to deselect all others )
and then key can move it around the canvas