Self rendering objects?

I have modified the sketch so the self-rendering object can be invisible. The ‘v’ key toggles visibility.

Button b;

void setup() {
  size(300, 200);
  b = new Button(this, 30, 20, 200, 30);
}

void draw() {
  background(255, 255, 200);
  fill(0);
  textSize(16);
  text("Hit 'v' to make visible / invisible", 30, 100);
}

void keyReleased() {
  if (key == 'v') {
    b.setVisible(!b.isVisible());
  }
}

public class Button {

  PApplet pa;
  int x, y, w, h;
  boolean visible = true;

  public Button(PApplet pa, int x, int y, int w, int h) {
    this.pa = pa;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h; 
    pa.registerMethod("draw", this);
  }

  public void setVisible(boolean visible) {
    this.visible = visible;
  }

  public boolean isVisible() {
    return visible;
  }

  public void draw() {
    if (visible) {
      pa.pushMatrix();
      pa.pushStyle();
      pa.fill(180, 180, 255);
      pa.stroke(0, 0, 128);
      pa.strokeWeight(2);
      pa.translate(x, y);
      pa.rect(0, 0, w, h);
      pa.popStyle();
      pa.popMatrix();
    }
  }
}
3 Likes