// 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.");
    }
  }
  
  // Useful debugging code for listing all the methods in a class
  // Ref: http://java.sun.com/docs/books/tutorial/reflect/class/getMethods.html
  public void listMethods(Object o) {
    Class c = o.getClass();
    Method[] theMethods = c.getMethods();
    for (int i = 0; i < theMethods.length; i++) {
       String methodString = theMethods[i].getName();
       System.out.println("Name: " + methodString);
       String returnString =
         theMethods[i].getReturnType().getName();
       System.out.println("   Return Type: " + returnString);
       Class[] parameterTypes = theMethods[i].getParameterTypes();
       System.out.print("   Parameter Types:");
       for (int k = 0; k < parameterTypes.length; k ++) {
          String parameterString = parameterTypes[k].getName();
          System.out.print(" " + parameterString);
       }
       System.out.println();
    }
  }
  
}

