2013-07-26 23 views
0

我只是用java輸入用戶輸入。我最初開始使用KeyListener,然後被告知使用KeyBindings。當我按下右箭頭鍵時,似乎無法使動畫測試移動。這是實現鍵綁定的正確方法,還是我需要在這些方法之一中添加某些內容?還有可能把所有的輸入方法(處理鍵綁定的方法)放到另一個可以從中訪問的類中?我的主要問題是無法使用右箭頭鍵移動動畫測試。使用KeyBindings

public class EC{ 
    Animation test = new Animation(); 
    public static void main(String args[]) 
    { 
     new EC(); 
    } 

    public EC() 
    { 
     JFrame window=new JFrame("EC"); 
     window.setPreferredSize(new Dimension(800,600)); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.add(test); 
     window.pack(); 
     window.setVisible(true); 
     addBindings(); 
    } 

    public void addBindings() 
    { 

     Action move = new Move(1,0); 
     Action stop = new Stop(); 
     InputMap inputMap = test.getInputMap(); 
     ActionMap actionMap = test.getActionMap(); 
     KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS); 
     inputMap.put(key,"MOVERIGHT"); 
     actionMap.put("MOVERIGHT",move); 
     key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_RELEASE); 
     inputMap.put(key, "STOP"); 
     actionMap.put("STOP", stop); 
    } 
    class Move extends AbstractAction 
    { 
     private static final long serialVersionUID = 1L; 
     int dx,dy; 
     public Move(int dx,int dy) 
     { 
      this.dx=dx; 
      this.dy=dy; 
      test.startAnimation(); 
      test.update(); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      test.x+=dx; 
      test.y+=dy; 
      test.repaint(); 
     } 
    } 
    class Stop extends AbstractAction 
    { 
     int dx,dy; 
     private static final long serialVersionUID = 1L; 
     public Stop() 
     { 
      test.stopAnimation(); 
      test.update(); 
     } 
     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      // TODO Auto-generated method stub 
      dx=0; 
      dy=0; 
      test.repaint(); 
     } 

    } 




} 
+0

在上一個問題中給出了一個工作示例:http://stackoverflow.com/questions/17864565/control-image-with-arrow-keys。你爲什麼不效仿這個例子? – camickr

+0

更多[示例](http://stackoverflow.com/questions/15422488/java-keybindings/15422641#15422641),[示例](http://stackoverflow.com/questions/15753551/java-keybindings-how-does - 它工作/ 15753582#15753582) – MadProgrammer

回答

1

很難說喲肯定,但你可能會喜歡嘗試像test.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)而不是。

另外KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS);是不正確的。第二個參數是指對於像CTRLALT移的修改屬性

在你的情況KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);會更正確

如果你有興趣在行動開始時調用的鍵,然後用類似...

KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false); 

或者,如果你只是想知道什麼時候它的發佈,使用類似

KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true);