We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi! How to make my custom event handler and event class that fires an event every second by updating a integer value?
I was following this tutorial Library-Basics.
What i actually much want to accomplish is pretty much the same as in the sDrop library-basic example, to use my own kind of event handler. I don't really know how to actually fire an event as described here: Describing Your Library --> public void makeEvent(EventClass event)
Let's say EventClass is updating a value every second which i want to treat as a fake event. In the main Sketch i want to get the updated value like this:
void fancyEvent(EventClass event){
println(event.count);
}
Now, how can i actually make that EventClass to fire an Event every second and updating (int)count and listen to it?
thx!
/ / / / / / / / / / / / / / / / / / / / /
So after an intensive day of research about reflection i found the solution.
import processing.core.*; // registerMethod
import java.lang.reflect.*;
EventObj obj;
Handler hand;
void setup(){
hand = new Handler(this);
obj = new EventObj(hand);
}
void draw(){ }
// handler method
void getSth(EventObj event){ println( event.getVal() ); }
// fire an event in the EventObj Object
void mousePressed(){ obj.process(); }
// This class handles the EventObj-Event
public class Handler {
private Method myMethod;
protected Object parent;
protected PApplet parentSketch;
public Handler(PApplet parent){ // Object theObject
this.parent = parent;
Class myClass = parent.getClass();
parent.registerMethod("dispose", this);
try {
myMethod = myClass.getDeclaredMethod("getSth", new Class[] { EventObj.class } );
myMethod.setAccessible(true);
} catch (Exception e) { println(e); }
}
protected void invokeEvent(EventObj event){
try {
myMethod.invoke( parent, new Object[] { event });
println("Handler received event from an EventObj-Object.");
} catch (Exception e) { println(e); }
}
public void dispose(){ System.out.println("Handler says bye."); }
}
// This Class fires an Event and passes it to the Handler Object
public class EventObj {
Handler handler; int val = 0;
protected EventObj(Handler theHandler){ handler = theHandler; }
public int getVal(){ return this.val; }
// this will tell the Handler Object than an event happened.
protected void process() {
val++; // the actuall event.
println("EventObj fired an Event.");
handler.invokeEvent(this); }
}
/*
Outputs:
EventObj fired an Event.
1
Handler received event from an EventObj-Object.
EventObj fired an Event.
2
Handler received event from an EventObj-Object.
EventObj fired an Event.
3
Handler received event from an EventObj-Object.
Handler says bye.
*/