2013-07-24 3 views
0

질문 : JTree에 키 바인딩을 추가 할 때 왜 각 액션을 자신의 클래스로 만들어야합니까? 각 작업마다 단일 Action 클래스를 사용할 수없는 이유는 무엇입니까? 내 질문/문제를 이해하려면 아래의 문제의 짧은 자기 포함 예제를 설명하여 시작하겠습니다.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에 대해 작업해야 함을 보여줍니다.) KeyAction 클래스를 만들 수있는 유일한 방법은 AbstractAction 클래스를 만드는 것이 었습니다 아래의 예제 코드에서 볼 수있는 각 액션,)

import java.awt.event.ActionEvent; 
import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.JFrame; 
import javax.swing.JPopupMenu; 
import javax.swing.JTree; 
import javax.swing.KeyStroke; 

public class StackExchangeQuestion2 { 
    public static void main(String[] args){ 
    StackExchangeQuestion2 workaround = new StackExchangeQuestion2(); 
    //workaround = compiler didn't like me throwing constructor code in main 
    }//end main 

StackExchangeQuestion2(){ 
    JTree tree = new JTree(); 
    initRightClickMenu(tree);//purpose of existance is to show Action Code is accurate 
    addKeyBindings(tree); 

    JFrame window = new JFrame(); 
    window.getRootPane().setContentPane(tree); 
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    window.setTitle("Stack Exchange Question"); 
    window.setSize(400,500);//variable parameters would be best 
    window.setVisible(true);   
    }//constructor 

private void initRightClickMenu(JTree tree){ 
    JPopupMenu rightclickmenu = new JPopupMenu(); 
    Action addsiblingnodeaction = new RightClickNodeAction("Add SiblingNode"); 
    Action addchildnodeaction = new RightClickNodeAction("Add ChildNode"); 
    rightclickmenu.add(addsiblingnodeaction); 
    rightclickmenu.add(addchildnodeaction); 
    tree.setComponentPopupMenu(rightclickmenu);   
} 

private void addSiblingNode(){ 
System.out.println("sibling node added");} 
private void addChildNode(){ 
System.out.println("child node added");}  


private void addKeyBindings(JTree tree){ 
//Action addsiblingnodeaction = new RightClickNodeAction("Add SiblingNode"); 
Action addsiblingnodeaction = new AddSiblingNodeAction("Add SiblingNode"); 
    tree.getActionMap().put("Add SiblingNode", addsiblingnodeaction); 
    tree.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Add SiblingNode");  
//Action addchildnodeaction = new RightClickNodeAction("Add ChildNode"); 
Action addchildnodeaction = new AddChildNodeAction("Add ChildNode");  
    tree.getActionMap().put("Add ChildNode", addchildnodeaction); 
    tree.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "Add ChildNode"); 
}//end addKeyBindins  

private class AddSiblingNodeAction extends AbstractAction{  
    AddSiblingNodeAction(String name){super(name);} 
    public void actionPerformed(ActionEvent ae) { addSiblingNode(); }} 

private class AddChildNodeAction extends AbstractAction{  
    AddChildNodeAction(String name){super(name);} 
    public void actionPerformed(ActionEvent ae) { addChildNode();  }}  

private class RightClickNodeAction extends AbstractAction{  
    RightClickNodeAction(String name){super(name);} 
    public void actionPerformed(ActionEvent ae) { 
    if(ae.getActionCommand().equals("Add SiblingNode"))addSiblingNode(); 
    if(ae.getActionCommand().equals("Add ChildNode"))addChildNode();  }} 
}//end class 
+0

이 작업 자체가 예상대로하면'addKeyBindings (JTree에 트리)에, 그러나, 작동, IDE에서 코드를 포함'당신이 주석 액션 코드 스위치는 작동을 멈 춥니 다/아무 반응이 없습니다. (ENTER/SPACE를 누르는 메시지를 찾으려고합니다.) – neokyle

+0

'System.out.println ("액션 명령은"+ ae.getActionCommand()); "클래스를 RightClickNodeAction 클래스에 추가하는 것입니다. 그리고 주석 처리 된 2 줄을 전환하는 것은 디버깅/그림을 찾는 데 도움이되는 것처럼 보이지만 ActionCommand String은 keyBindings (JTree의 입력 맵에 대한)에 대한 어떤 이유 때문에 null이지만 JPopupMenu의 경우 예상대로 – neokyle

+0

'Action'은'actionCommand'를 설정하지 않습니다. 항상 'null'입니다. 대신 당신은'NAME' 속성 ('get (NAME)')을 얻고, – MadProgrammer

답변

0

답변 : 내가 잘못하고 있어요 때문에, 나는 한 가지 방법을하도록 강요하고 있지 않다. 당신이 때리는 경우

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();  }} 
+0

생성자에'putValue (ACTION_COMMAND_KEY, name);'를 추가하고 ActionEvent ae를 고정시켜 모든 경우에 ae.getActionCommand가 유효한 값을 갖도록했습니다 – neokyle