Execute code on PGraphics

Hi, i have a quesetion! I have a class:

class Thing {
int x = 0;
Thing() {
x = 50;
}
void create(int x_) {
this.x = x_;
}
void display() {
circle(width/2, height/2, x);
}
}

i also have a Pgraphics:

PGraphics ui;

void setup() {
size(960,540,P3D);
ui = createGraphics(100,100);
}
void draw() {
background(255);
image(ui, 0, 0);
}

I now want to make an instance of the Thing class. I want it to be displayed on top of the pgraphics. however i do not want to make the Thing class be dependent on the pgrahics, (every drawing in the class happens on the graphics). I want to be able to do something like this:

PGraphics ui;
Thing instance;

void setup() {
  size(960, 540, P3D);
  ui = createGraphics(100, 100);
  instance = new Thing();
  instance.create(100);
}
void draw() {
  background(255);
  image(ui, 0, 0);
  ui.beginDraw();
  ui.clear();
  ui.instance.display();
  ui.endDraw();
}

class Thing {
  int x = 0;
  Thing() {
    x = 50;
  }
  void create(int x_) {
    this.x = x_;
  }
  void display() {
    circle(width/2, height/2, x);
  }
}

Thank you for your patience!
-Noodly

You have to pass the PGraphics that you want to use into your display() function. Also, image() the PGraphics after you draw to it, not before.

class Thing {
  void display( PGraphics pg ) {
    pg.circle( pg.width/2, pg.height/2 );
  }
}

void draw() {
  background(255);
  ui.beginDraw();
  ui.clear();
  instance.display( ui );
  ui.endDraw();
  image( ui, 0, 0 );
}
2 Likes