Remark
sub = new ArrayList <SubGrid>(); //
this deletes the whole thing
Remark
without background (255); at start of draw() you see the accumulated results of all drawings.
You can’t really see what the last mousePressed did!
Remark
I think this doesn’t do what you want:
rect (x, y, w/2, h/2);
rect (x, y/2, w/2, h/2);
rect (x/2, y, w/2, h/2);
rect (x/2, y/2, w/2, h/2);
for example, the rects are called with
0.0 0.0
100.0 0.0
200.0 0.0
300.0 0.0
400.0 0.0
500.0 0.0
600.0 0.0
700.0 0.0
800.0 0.0
in the first round.
but e.g. this line rect (x/2, y, w/2, h/2); results in
rect (0, 0, w/2, h/2);
rect (50, 0, w/2, h/2);
rect (100, 0, w/2, h/2);
rect (150, 0, w/2, h/2);
so it’s far more left than the initial rect (x, y, w/2, h/2);
That’s why you see the gaps on the right.
Here is my version of the code section (one cell is divided into four cells):
fill( 255, 0, 0 );
rect (x, y, w/2, h/2);
fill( 0, 255, 0);
rect (x, y+h/2, w/2, h/2);
fill( 0, 0, 255);
rect (x+w/2, y, w/2, h/2);
fill( 255, 0, 255);
rect (x+w/2, y+h/2, w/2, h/2);
Full Sketch
Full Sketch to demonstrate some of the above
ArrayList <GridCell> grid;
ArrayList <SubGrid> sub;
float w;
float yNew = 0;
void setup() {
size (800, 400);
background (255);
grid = new ArrayList <GridCell>();
sub = new ArrayList <SubGrid>();
w = width/8;
float h = height;
for (float x = 0; x <= width; x+=w) {
grid.add(new GridCell(x, 0,
w, h-=9));
}
}
void draw() {
background (255);
//float h = width/8;
for (int i = 0; i < grid.size(); i++) { // can use short form of for-loop here
grid.get(i).display();
}
for (int j = 0; j < sub.size(); j++) {// can use short form of for-loop here
sub.get(j).display();
}
}
//---------------------------------------------------------------------------------
void mousePressed() {
sub = new ArrayList <SubGrid>(); // this deletes the whole thing
float w = width/8;
float h = w;
for (int i = 0; i < grid.size(); i++) {
if (mouseX>grid.get(i).x&&
mouseX<grid.get(i).x+w ) {
sub.add(new SubGrid(grid.get(i).x, yNew, w, h));
}
}
yNew = yNew+55;
}
//MAIN GRID CLASS //////////////////////////////////
class GridCell {
float x, y;
float w, h;
GridCell(float x_, float y_,
float w_, float h_) {
x = x_;
y = y_;
w = w_;
h = h_;
}
void display() {
stroke(0);
noFill();
rect (x, y,
w, h);
}
}//class
//SUBGRID CLASS //////////////////////////////
class SubGrid {
float x, y;
float w, h;
color col1 = color(random(255), random(255), random(255), 50); // set random color at the start of the class, so we don't have a flickering color
color col2 = color(random(255), random(255), random(255), 50); // set random color at the start of the class, so we don't have a flickering color
SubGrid(float x_, float y_,
float w_, float h_) {
x = x_;
y = y_;
w = w_;
h = h_;
}
void display() {
stroke(0);
fill( 255, 0, 0 );
rect (x, y, w/2, h/2);
fill( 0, 255, 0);
rect (x, y+h/2, w/2, h/2);
fill( 0, 0, 255);
rect (x+w/2, y, w/2, h/2);
fill( 255, 0, 255);
rect (x+w/2, y+h/2, w/2, h/2);
}
}//class
//
Chrisir