所以我正在制作一个自定义菜单,这是处理调用正确方法的子菜单项类。目前我正在使用switch语句作为方法名称,但这是最好的方法吗?
我会喜欢一双新的眼睛,我一直在寻找这种方式。谢谢!
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 was provided for 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) {
}
}
动作类(只有2个方法atm但会有更多)
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();
}
}
答案 0 :(得分:1)
使用命令模式:
在面向对象的编程中,命令模式是一种行为 设计模式,其中一个对象用于表示和封装 稍后调用方法所需的所有信息。这个 信息包括方法名称,拥有该方法的对象 和方法参数的值。
来自http://en.wikipedia.org/wiki/Command_pattern
此示例与您的问题非常相似:
http://alvinalexander.com/java/java-command-design-pattern-in-java-examples