# \[SOLVED\] Scalable grid with rectangles

**URL:** <https://discourse.processing.org/t/solved-scalable-grid-with-rectangles/7256>\
**Category:** Coding Questions\
**Created:** [January 6, 2019, 8:53pm UTC](https://discourse.processing.org/t/solved-scalable-grid-with-rectangles/7256 "2019-01-06T20:53:16Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 7, 2019, 9:12am UTC](https://discourse.processing.org/t/solved-scalable-grid-with-rectangles/7256/6 "2019-01-07T09:12:59Z")

</div>

> [@blue-man](#):
>
> The problem is, that every rectangle must be an own object.  
> With your code I can create a grid, but I cant choose the single rectangle in the grid.  
> My goal is, that I can choose the single rectangle.

the math is still the same,

- if you draw a grid of rect OR
- setup your own array of rectangles from class

> **example**
>
> ```auto
> // https://discourse.processing.org/t/scalable-grid-with-rectangles/7256
> int x = 20, y = x, w = 0, h = w;
> int grid = 8, many = grid*grid;
> 
> Myrect[] myrects= new Myrect[many];
> 
> void setup() {
> size(600, 400);
> // use x,y,grid as master and auto adjust rectangles (w,h) to window:
> w = ( width - 2 * x ) / grid;
> h = ( height - 2 * y ) / grid;
> for (int i = 0; i < many; i++) myrects[i]=new Myrect(x+(i%grid)*w, y+(floor(i/grid))*h);
> println("use: mouse LEFT to select, mouse RIGHT to deselect");
> }
> 
> void draw() {
> background(200, 200, 0);
> for (int i = 0; i < many; i++) {
> myrects[i].drawit(); // draw each rect   
> myrects[i].sel(); // check if mousebutton and over this for color
> }
> }
> 
> class Myrect {
> int x, y;//, w, h; from global
> boolean selected=false;
> Myrect (int x, int y) {
> this.x = x; 
> this.y = y;
> }
> void drawit() {
> stroke(0, 0, 200);
> if ( selected ) fill(0, 200, 0);
> else fill(200, 0, 200);
> rect(x, y, w, h);
> }
> boolean over() {
> return( x < mouseX && mouseX < x+w && y < mouseY && mouseY < y+h );
> }
> void sel() {
> if ( over() ) {
> if ( selected && mousePressed && mouseButton == RIGHT) selected=false;
> if ( !selected && mousePressed && mouseButton == LEFT) selected=true;
> }
> }
> }
> 
> ```

---

_[View the full topic](https://discourse.processing.org/t/solved-scalable-grid-with-rectangles/7256)._
