# Creating a clickable dynamic grid

**URL:** <https://discourse.processing.org/t/creating-a-clickable-dynamic-grid/26259>\
**Category:** Coding Questions\
**Created:** [December 15, 2020, 10:14am UTC](https://discourse.processing.org/t/creating-a-clickable-dynamic-grid/26259 "2020-12-15T10:14:04Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![MiguelSanches](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/miguelsanches/32/11172_2.png) [@MiguelSanches](https://discourse.processing.org/u/MiguelSanches)\
**Post date:** [December 15, 2020, 11:25am UTC](https://discourse.processing.org/t/creating-a-clickable-dynamic-grid/26259/2 "2020-12-15T11:25:57Z")

</div>

Hi @Reynaert98,

This is a simple example that I made for better understanding.  
The main idea is the following:

1. 
  - A card class represents a card, which has determined position and dimensions.

2. 
  - To draw a card, I used a rectangle centered in x and y using the dimensions below. So I draw the rectangle and consider the spacing for the margin

![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/5/566d96a664de7ce0aeaf11298812dca505a6dd11.png)  
3) - By knowing the dimensions of each card I can know if the mouse is on top of the card (hover() method).  
4) - An ArrayList of cards has as many cards as you want. So setting n, in the beginning, allows choosing the number of cards to make a grid

Thus, when the mouse is pressed I check which card had the mouse on top of it and so I set a new Color for the card

```auto
int n = 3;
ArrayList<Card> cards;
void setup() {
  size(600, 600);
  cards = new ArrayList();
  for (int i = 1; i <= 2*n; i++) {
    for (int j = 1; j <= 2*n; j++) {
      if (i % 2 == 1 && j%2 ==1) cards.add(new Card(i*width/(2*n), j*height/(2*n), width/n, height/n));
    }
  }
}

void draw() {
  for (int i = 0; i < cards.size(); i++) {
    cards.get(i).display();
  }
}

void mousePressed() {
  for (int i = 0; i < cards.size(); i++) {
    if (cards.get(i).hover()) {
      cards.get(i).setColor(color(0, 255, 0));
    }
  }
}

class Card {
  int xpos, ypos, cardWidth, cardHeight;
  color c1;
  int spacing;
  Card(int _x, int _y, int _w, int _h) {
    xpos = _x;
    ypos = _y;
    cardWidth = _w;
    cardHeight = _h;
    c1 = color(255, 0, 0);
    spacing = 30;
  }

  void display() {
    stroke(255);
    fill(c1);
    rectMode(CENTER);
    rect(xpos, ypos, cardWidth - spacing, cardHeight - spacing);
    noFill();
    noStroke();
  }

  boolean hover() {
    return (mouseX > xpos - cardWidth/2 && mouseX < xpos + cardWidth/2 
      && mouseY > ypos - cardHeight/2 && mouseY < ypos + cardHeight/2);
  }

  void setColor(color newColor) {
    c1 = newColor;
  }
}

```

Hope this helps or at list gives you a hint to solve your problem 🙂

Best regards

---

_[View the full topic](https://discourse.processing.org/t/creating-a-clickable-dynamic-grid/26259)._
