Turning randomly placed buttons off and on via boolean switch

I think this is a question about program flow and how to enable user interaction.
Currently working on a problem in Shiffman book.

  • I want to create multiple buttons (currently 2 buttons in this version) via object class iteration.
  • When I mouse click within a button area, button color changes.

I am not seeing the desired on / off interaction via boolean switch.
Code below:
////////////////////////////////////////////////

Button b1;
Button b2;

void setup() {
  size (600, 600);
  b1 = new Button(random(width), random(height), random(50, 100));
  b2 = new Button(random(width), random(height), random(50, 100));
}

void draw() {

  b1.display();
  b2.display();

  b1.click();
  b2.click();
}
void mousePressed() {

  if (mouseX > x && mouseX < x + sz && mouseY > y && mouseY < y + sz) {
    on = !on;
  }
}

CLASS//////////////////////////////////////////////////

class Button {
  float x;
  float y;
  float sz;
  boolean on;

  Button(float tempX, float tempY, float tempSz) {
    x = tempX;
    y = tempY;
    sz = tempSz;

    on = false;
  }

  void display() {
    rect (x, y, sz, sz);
  }


  void click() {

    if (on) {
      fill (255);
      stroke(0);
    } else {
      fill (0);
      stroke (255);
    }

    if (mouseX > x && mouseX < x + sz && mouseY > y && mouseY < y + sz) {
      on = !on;
    }
  }
}

Any guidance most welcomed!! :slightly_smiling_face: :slightly_smiling_face:

1 Like


Button b1;
Button b2;

void setup() {
  size (600, 600);
  b1 = new Button(random(width), random(height), random(50, 100));
  b2 = new Button(random(width), random(height), random(50, 100));
}

void draw() {
  b1.display();
  b2.display();
}

// -----------------------------------------------------------------------------------

void mousePressed() {
  b1.click();
  b2.click();
}

//============================================================================
// CLASS//////////////////////////////////////////////////

class Button {
  float x;   // pos 
  float y;
  float sz; // size 
  boolean on;

  Button(float tempX, float tempY, 
    float tempSz) {
    x = tempX;
    y = tempY;
    sz = tempSz;

    // check against right and lower screen border 
    if (x+sz>=width)
      x=width-sz-1; 

    if (y+sz>=height)
      y=height-sz-1; 

    on = false;
  }

  void display() {

    // eval and use on HERE 
    if (on) {
      fill (255);
      stroke(0);
    } else {
      fill (0);
      stroke (255);
    }

    rect (x, y, sz, sz);
  }


  void click() {
    if (mouseX > x &&
      mouseX < x + sz && 
      mouseY > y && 
      mouseY < y + sz) {
      on = !on;
    }
  }
  //
}
//
1 Like

that was the main problem.

It belongs in the class.

I now call click from mousePressed, instead of from draw

3 Likes

Ah!! That makes sense!
Thank you @Chrisir
:grinning:

2 Likes