2017-11-29 53 views
0

키 바인더가 어떻게 작동하는지 배우려고하고 있습니다. 자바 튜토리얼에서 오해 한 것 같습니다. 이 코드입니다 : 내가 이해에서키 바인드가 작동하지 않고, 액션이 수행되지 않았습니다.

public class KeyBinder { 

    public static void main(String[] args) { 

     //making frame and label to update when "g" key is pressed. 

     JLabel keybinderTestLabel; 

     JFrame mainFrame = new JFrame(); 
     mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainFrame.setSize(300,75); 
     mainFrame.setLocationRelativeTo(null); 
     mainFrame.setVisible(true); 

     keybinderTestLabel = new JLabel("Press the 'g' key to test the key binder."); 
     mainFrame.add(keybinderTestLabel); 

     Action gPressed = new AbstractAction(){ 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       keybinderTestLabel.setText("Key Binding Successful."); 
       System.out.println("Key Binding Successful."); 
       //Testing to see if the key binding was successful. 
      } 

     }; 


     keybinderTestLabel.getInputMap().put(KeyStroke.getKeyStroke("g"), "gPressed"); 
     keybinderTestLabel.getActionMap().put("gPressed", gPressed); 
     /* 
     * from my understanding, these two lines map the KeyStroke event of the g key 
     * to the action name "gpressed", then map the action name "gpressed" to the action 
     * gpressed. 
     * 
     */ 
    } 

} 

, 내가 작업 이름 "gPressed"에 g 키 입력을 매핑 한 다음 매핑하는 작업 gPressed에. 그러나 어떤 이유로 프로그램을 실행할 때 g 키를 누르면 텍스트 레이블이 업데이트되지 않습니다. 여기에 무슨 문제가 있니? 키보드의 g 키에 실제로 매핑되지 않은 "g"키 입력입니까?

답변

3

그래서, JavaDoc을에서

public final InputMap getInputMap() 구성 요소에 포커스가있는 경우 을 사용하는 InputMap를 돌려줍니다. 이는 getInputMap(WHEN_FOCUSED)의 편리한 방법입니다. JLabel 이후

가 포커스 아니라,이 ... 대신에, 당신은 예를 들어, 다른 초점 조건을 제공해야합니다, 또한

keybinderTestLabel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). //... 

작동하지 않습니다, 이것은 개인적인 취향입니다 .. KeyStroke.getKeyStroke("g")을 사용하면 을 사용하는 것은 문제가 될 수 있습니다. String을 제공하는 것은 그 의미가 매우 정확해야하며 정확하게 작동하는 방법을 기억하지 못합니다 (과도하게 문서화되지 않았습니다). 작동하지 않습니다 - 첫번째 제안은 문제를 해결하지 못할 경우

, 대신

+1

은 (1+)'KeyStroke.getKeyStroke ("g")는'KeyStroke.getKeyStroke(KeyEvent.VK_G, 0)를 사용해보십시오. String를 사용하려면, 다음을 사용할 수 있습니다 :'KeyStroke.getKeyStroke ("G")'. 키보드의 "g"를 누르기위한 바인딩을 등록 할 경우. 문자열을 사용하면 기본적으로 KeyEvent.VK _ 뒤에 텍스트를 가져옵니다. 따라서'KeyStroke.getKeyStroke ("ENTER")'를 사용하여 "Enter"키를 청취 할 수도 있습니다. 또는 이해하기 쉽도록 문자 매개 변수를 사용하는 것입니다 :'KeyStroke.getKeyStroke ('g')', – camickr

+0

아, 고마워! 그러나 getKeyStroke (KeyEvent.VK_G, 0)를 사용하면 0 매개 변수는 무엇을 수행합니까? – Psear

+0

@Psear 수정 자 (예 : 이동/변경/제어) – MadProgrammer