It’s because the ControlP5() constructor accepts the following arguments (from the library’s javadoc ):
ControlP5(processing.core.PApplet theParent)
Create a new instance of controlP5.
So when you are using it in your class, the keyword this refers to the current instance of your class but not the PApplet which is the wrapper class of your Processing sketch.
Instead, you can eventually pass the PApplet instance to the constructor of your class :
import controlP5.*;
class MyClass {
ControlP5 cp5;
MyClass(PApplet parent) {
cp5 = new ControlP5(parent);
}
}
// Instanciate it
MyClass instance = new MyClass(this);
For the event handler, I think that it’s the reason behind passing the PApplet object to the constructor because they can now call some methods that you define in your main program.
If you put it in your class, then it’s no more accessible in the main PApplet class.
In the source code, they check for a method called controlEvent :
// ControlP5.java
_myControlBroadcaster = new ControlBroadcaster( this );
// ControlBroadcaster.java
// ...
private String _myControllerCallbackEventMethod = "controlEvent";
// ...
_myControlEventPlug = checkObject( cp5.papplet , getEventMethod( ) , new Class[] { ControlEvent.class } );
// ...
protected static ControllerPlug checkObject( final Object theObject , final String theTargetName , final Class< ? >[] theAcceptClassList ) {
// ...
ControllerPlug cp = new ControllerPlug( CallbackEvent.class , theObject , theTargetName , ControlP5Constants.EVENT , -1 );
// ...
}
// Then in ControllerPlug.java
/* check for methods */
if ( _myType == ControlP5Constants.METHOD ) {
try {
Method[] myMethods = myClass.getMethods( );
// ...
/* check for controlEvent */
} else if ( _myType == ControlP5Constants.EVENT ) {
try {
_myMethod = _myObject.getClass( ).getMethod( _myName , new Class[] { _myEventMethodParameter } );
_myMethod.setAccessible( true );
_myParameterClass = _myEventMethodParameter;
// And so on...
I don’t know if it’s possible to specify a custom class with an event handler…
So maybe my approach is just wrong.
If I leave the event listener outside the class and instantiate p5 inside the class, the UI works but after a while, I get many errors in the console, and Java crashes.
I’m trying to create a class that has its own UI. What would be the right approach here?
Maybe you can pass an instance of the controlP5 class to all of your classes, it’s the same principle with the previous example I wrote with the PApplet.
So in the constructor of your class, you can create all your widgets with the instance of conrolP5.