Java 在向JTree添加键绑定时,为什么我必须使每个操作都是它';她是自己的班级吗?

Java 在向JTree添加键绑定时,为什么我必须使每个操作都是它';她是自己的班级吗?,java,swing,action,jtree,key-bindings,Java,Swing,Action,Jtree,Key Bindings,问题:在向JTree添加键绑定时,为什么我必须使每个操作都成为自己的类? 为什么我不能让每个动作都使用一个动作类? 为了理解我的问题,让我首先解释一下我下面这个简短的自我包含的问题示例 addKeyBindings(JTree tree) has the following 2 lines commented out. //Action addsiblingnodeaction = new RightClickNodeAction("Add SiblingNode"); //Action ad

问题:在向JTree添加键绑定时,为什么我必须使每个操作都成为自己的类? 为什么我不能让每个动作都使用一个动作类? 为了理解我的问题,让我首先解释一下我下面这个简短的自我包含的问题示例

addKeyBindings(JTree tree) has the following 2 lines commented out. 
//Action addsiblingnodeaction = new RightClickNodeAction("Add SiblingNode");
//Action addchildnodeaction = new RightClickNodeAction("Add ChildNode");
/*These use 1 action class, to do 2 different actions. (I want this because I 
find the code to be less verbose)
(They're commented out because they don't work for keybindings)
(The reason I ask question, is because they DO work for JPopupMenu)*/
真正的问题是,为什么上面的//注释掉的代码//不适用于键绑定?(在我的示例中,我包括了一个JPopupMenu,以表明上面注释掉的代码适用于JPopupMenu,在我看来也适用于键绑定)(我能够让keybindings工作的唯一方法是为每个动作创建一个AbstractAction类,您可以在下面的示例代码中看到)


回答:因为我做错了,所以我不是被迫用一种方式来做的

private class RightClickNodeAction extends AbstractAction{      
    RightClickNodeAction(String name){super(name);
    putValue(ACTION_COMMAND_KEY, name); 
    }//end constructor
public void actionPerformed(ActionEvent ae) {
   //System.out.println("Action Command is: "+ae.getActionCommand());
   //the above comment verified it worked as expected + testing
if(ae.getActionCommand().equals("Add SiblingNode"))addSiblingNode();
if(ae.getActionCommand().equals("Add ChildNode"))addChildNode();     }}

如果您在IDE中使用这个工作的自包含代码,它将按预期工作,但是,如果在
addKeyBindings(JTree树)
中切换注释的操作代码,它将停止工作/什么也没有发生。(您在按ENTER/SPACE时查找要打印的消息)哼哼添加
System.out.println(“操作命令是:+ae.getActionCommand())
到类RightClickNodeAction。切换这两个注释掉的行似乎有助于调试/确定,ActionCommand字符串由于键绑定(到JTree的输入映射)的某些原因为空,但正如预期的那样,JPOppMenu
Action
不会设置
actionCommand
,因为它总是
null
。相反,您可以尝试获取
NAME
属性(
get(NAME)
)比较一下,我在第二条评论中提到过,对于JPOppMenu,actionCommand不是空的,但是感谢您给我提供了java文档的概念,也许在构建过程中有一些方法可以设置它。“actionCommand对于JPOppMenu不是空的”-它应该只需要添加
putValue(ACTION\u COMMAND\u KEY,name);
到构造函数,它修复了它/初始化了ActionEvent ae,以便ae.getActionCommand在所有情况下都具有有效值
private class RightClickNodeAction extends AbstractAction{      
    RightClickNodeAction(String name){super(name);
    putValue(ACTION_COMMAND_KEY, name); 
    }//end constructor
public void actionPerformed(ActionEvent ae) {
   //System.out.println("Action Command is: "+ae.getActionCommand());
   //the above comment verified it worked as expected + testing
if(ae.getActionCommand().equals("Add SiblingNode"))addSiblingNode();
if(ae.getActionCommand().equals("Add ChildNode"))addChildNode();     }}