Creating listener classes

Im new to openFrameworks. I’ve been trying to do something i did in Java and i cant figure out how. I need to do something similar for multiple event types, but imo once i figure out how to do this basic button, i should be fine with the rest. Basically:

I made an “ofxButton” named “m_drawCircleButton”. I want to create a class named “DrawCircleAction”. An object of that class would be assigned to the button as a listener. It should look a bit like this.

in “ofApp”, i would have something like :

DrawCircleAction m_drawCircleAction;

m_drawCircleButton.addListener(m_drawCircleAction);

in the class “DrawCircleAction”, i would have something like:

void onButtonPress() {
// do something when the button is pressed.
}

Maybe ofEvent is what you need
https://openframeworks.cc/documentation/events/ofEvent/

I looked at it before posting and i dont think thats what i am trying to do. I am not trying to create a custom event. From what i understood, ofxButton is already capable of generating an event. Im trying to create a class that is capable of listening to that event.

hello hello,
i usually use the underlying ofParameters/ofParameterGroup directly. and pass them to the gui.
these examples should make this approach a bit clearer.

hope that helps

1 Like

Hey @Thormind , I am not really sure what your DrawCircleAction class would do but if you want to have a class listening to an event you must use an ofEvent in the sender class and an ofEventListener in the listener (or use the oldschool ofAddListener(…) function).
Look at examples/events/simpleEventsExample as I think it does what you are looking for.
You might want to read the following for an in depth explanation and how to use of the ofEvents

1 Like

tks, i was able to figure it out. From what i understood, it’s a but different with ofxButton. They seem to already contain an "ofEvent. All i had to do was create a public method in my “DrawCircleAction” (i called it "void buttonPresswed()) and then link that method as a listener to the button:

m_drawCircleButton.addListener(&m_drawCircleAction, &DrawCircleAction::buttonPressed);

tks, im using “ofParameters” for most of my gui elements, but i wasnt able to find how to generate an ofxButton that way. The solution i found was quite simple though.

Hi @Thormind
I completely misread your original post.
It is way much simpler than all this. sorry.

// in ofApp.h
DrawCircleAction m_drawCircleAction;
ofxButton m_drawCircleButton

//in ofApp.cpp
// you set the listener where you want to, but most probably inside ofApp::setup() will be a good idea
m_drawCircleButton.addListener( &m_drawCircleAction, DrawCircleAction::onButtonPress); 

So, the add listener receives two parameters, first a pointer to the object that will listen (react to the event), and second the function of this object that will be called.

1 Like