Ok after some extensive and careful research I have acheived my goal. Below is a working example of creating a
Synthetic Event based on this tutorial/glossary:
http://mindprod.com/jgloss/event11.html
Synthetic events:
http://mindprod.com/jgloss/event11.html#SYNTHETICEVENTS
Essentially, instead of creating an event and then using listener interfaces to receive the event I am passing the event directly to the parent where I want to use it.
I opted to use the all encompasing ActionEvent (!an action happened) as a basis for my event type.
The class stores the values required to create the event. Then, when ready to fire you call the
eventName.sendEvent(Object parent); method which looks to see if
ActionPeformed(ActionEvent e); exists in the specified parent. If it exists, then the method is called and the event object passed over.
In normal usage Object parent will be
this passed down from your main code.
My implementation:
Code:// Method class required to check method exists
import java.lang.reflect.Method;
public class MyGUIActionEvent {
// values stored in an MyGUIActionEvent
private String _command;
private MyGUIObject _source;
Method actionEventMethod;
// construct data store for event
MyGUIActionEvent(MyGUIObject source, String command) {
// set variables
this._command = command;
this._source = source;
}
// send event directly to target (listener)
public void sendEvent(Object parent) {
// create ActionEvent
ActionEvent guiEvent = new ActionEvent(_source, ActionEvent.ACTION_PERFORMED, _command);
// check to see if the host applet implements
// public void actionPerformed(ActionEvent e)
try {
actionEventMethod = parent.getClass().getMethod("actionPerformed", new Class[] { guiEvent.getClass() });
actionEventMethod.invoke(parent, new Object[] { guiEvent });
}
catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
println("No method named actionPerformed was found in parent.");
}
}
}
Sample usage:
Code:
MyGUI gui;
MyGUIButton helloButton;
MyGUIActionEvent guiEvent;
void setup() {
gui = new MyGUI(this);
helloButton = new MyGUIButton(40, 20, "hello");
helloButton.setActionCommand("submit");
gui.add(helloButton);
}
void draw() {
}
void actionPerformed(ActionEvent e) {
// Check event based on its actionCommand
// Adv: several objects can have the same actionCommand
if(e.getActionCommand == "submit") {
println("hello button was clicked");
}
// Alternatively check event based off the object
if(e.getSource == helloButton) {
println("hello button generated this event");
}
}
This all works, I've tested it - I'm currently finalising my first ALPHA release of MyGUI and the MyGUIObject adapter, then adding documentation.