Connect a function to a button created in an object (ControlP5)

Hello all,

I have a class named “Interface” in witch I’m creating some buttons.
I want to execute a function when a button is pressed.
The problem is since I want my class to be generic, I can’t write that peace of code inside my class, I need it to be in my main code.
Is there a way, then, to connect a function to a button created inside an object.

The example below show what I would like to achieve :

Interface i;

void setup() {
  size(800, 600);
  i = new Interface(this);
  i.connectFunctionToBtn(functionToTrigger); //This is what I would like to write
}

void draw() {
  background(20);
}

void functionToTrigger() {
   println("Function triggered"); 
}

Then my class Interface would be something like this :

import controlP5.*;

class Interface {
 
  ControlP5 cp5;
  
  Interface(PApplet p_parent) {
    cp5 = new ControlP5(p_parent);
    
    cp5.addButton("btnTest")
    .setPosition(10, 10)
    .setSize(50,20);
  }
  
  // THE FUNCTION TO WRITE
  void connectFunctionToBtn() {
  }
}

Thank you for your help ! =D

Interface i;
void setup() {
  size(800, 600);
  i = new Interface(this, "functionToTrigger");
}
void draw() {
  background(20);
}
void functionToTrigger() {
   println("Function triggered"); 
}

import controlP5.*;
class Interface {
  ControlP5 cp5;
  Interface(PApplet p_parent, String buttonTriggersThis) {
    cp5 = new ControlP5(p_parent);
    cp5.addButton(buttonTriggersthis)
    .setPosition(10, 10)
    .setSize(50,20);
  }
}

You could do this? I haven’t actually tried running this…

2 Likes

Thanks a lot !

It is working like a charm :smiley:

Just by curiosity, would there be a way of doing this without giving the name of the function to the button ?

It would be a bit more elegant in my project :stuck_out_tongue:

In Processing, not really.
In other languages you could be mucking about with function pointers.

Yep , I was thinking abot something like that.

Too bad :confused:

http://www.Sojamo.de/libraries/controlP5/reference/controlP5/Controller.html#plugTo-java.lang.Object-java.lang.String-

// https://Discourse.processing.org/t/
// connect-a-function-to-a-button-created-in-an-object-controlp5/1821/7

// https://GitHub.com/sojamo/controlp5/blob/master/examples/extra/
// ControlP5ControllerInsideClass/ControlP5ControllerInsideClass.pde

// GoToLoop (2018/Jul/16)

import controlP5.ControlP5;

ControlP5 cp5;
Interface i;

void setup() {
  size(300, 200);
  i = new Interface(cp5 = new ControlP5(this));
}

void draw() {
  background(050);
}

class Interface {
  final ControlP5 cp5;

  Interface(final ControlP5 controlP5) {
    (cp5 = controlP5).addButton(getClass().getSimpleName())
      .setPosition(10, 10)
      .setSize(50, 20)
      .plugTo(this, "gotClicked");
  }

  void gotClicked() {
    println("You've clicked at me!");
  }
}