menu - Java Best way to invoke methods with a given string -


so i'm making custom menu , sub-menu item class handles invoking correct method. using switch statement method name, best way it?

i love new set of eyes, have been looking @ way long. thanks!

import java.awt.event.mouseevent; import java.awt.event.mouselistener; import javax.swing.jlabel;  import com.as.devcenter.util;  public class menusubitem extends jlabel implements mouselistener {      private static final long serialversionuid = 1l;      private string action = "";      public menusubitem(string label, string action, class<?> classname) {     addmouselistener(this);      this.action = action;      settext(label);     setname(action);     setsize(util.widthoftext(gettext(), util.getdefaultfont()) + 4, 22);     }      /*      * start mouse events      */      @override     public void mouseclicked(mouseevent e) {     util.log("menusubitem clicked");     if (action.equalsignorecase("")) {         util.log("no action provided menusubitem: " + gettext());     } else {         try {         method method = actions.class.getdeclaredmethod(action, classname);          switch (method.getname()) {         case "newproject":             newprojectframe npf = new newprojectframe();             method.invoke(npf, npf);             break;         case "openconsole":             console console = new console();             method.invoke(console, console);             break;         }         } catch (nosuchmethodexception | securityexception | illegalaccessexception | illegalargumentexception | invocationtargetexception e1) {         if (e1 instanceof nosuchmethodexception) {             util.log("could not identify action: " + action);         } else {             e1.printstacktrace();         }         }      }     }      public void mousepressed(mouseevent e) {     }      public void mousereleased(mouseevent e) {     }      public void mouseentered(mouseevent e) {     }      public void mouseexited(mouseevent e) {     } } 

actions class (just have 2 methods atm have more)

public class actions {      public static void newproject(newprojectframe npf){         npf.setup();         util.getprogram().items[0].clear();     }      public static void openconsole(console console){     console.setup();     util.getprogram().items[0].clear();     } } 

use command pattern:

in object-oriented programming, command pattern behavioral design pattern in object used represent , encapsulate information needed call method @ later time. information includes method name, object owns method , values method parameters.

from http://en.wikipedia.org/wiki/command_pattern

this example similar problem:

http://alvinalexander.com/java/java-command-design-pattern-in-java-examples


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -