Self rendering objects?


#1

Hello everybody!

I’m working on my own GUI project. Can someone point me on the right direction to make “self rendering objects”?

For example, ive got a class Buttons, i would like to make an instance of that class and the button render on the screen each frame without me having to call a MyButton.Render() function.

Thank you all.


#2

The following code shows how an object can ‘self-register’ to draw itself. In a GUI you will also need to register for mouse and key events more info can be found here.

Button b;

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

void draw() {
  background(255, 255, 200);
}

public class Button {

  PApplet pa;
  int x, y, w, h;

  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 draw() {
    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();
  }
}

Processing already has some GUI libraries you might look at G4P and ControlP5 :grinning:


#3

Hello quark!

Thank you for your reply! This will very helpfull.

Yes, i know there are some GUI libraries already, in fact, i’ve been using G4P for a long time and i love it, but i just wanted to do my own modest version :slight_smile:

Thank you again