2013-03-12 199 views
0

我有一個2人遊戲,一個玩家使用WASD,一個使用箭頭鍵。我無法弄清楚如何一次允許多個鍵。這裏是我的代碼:多鍵輸入

List keyArray = new ArrayList(); 

    // Red guy input. 
    if (e.getKeyCode() == 37) { // left key 

     new LoadRedCharacter("leftrightfootred.gif"); 

     int x = Frame.redCharacterLabel.getX(); 
     int y = Frame.redCharacterLabel.getY(); 
     if (x < 0) { 
      Frame.redHealthLabel.setLocation(x - 13, y - 15); 
      Frame.redCharacterLabel.setLocation(x + 1, y); 
      ResetEntities.redCharacterObj.setLocation(x + 1, y); 
     } else { 
      Frame.redHealthLabel.setLocation(x - 13, y - 15); 
      Frame.redCharacterLabel.setLocation(x - 2, y); 
      ResetEntities.redCharacterObj.setLocation(x - 2, y); 
     } 
     keyArray.add(37); 
     System.out.println("array" + keyArray); 
     Frame.frame.repaint(); 
     checkHitBox(); 
    } 

我也有藍色字符左移的代碼。然後我有這個:

 // Multi key input 
    if (keyArray.contains(37) && keyArray.contains(65)) { 
     System.out.print("array contains 37 and 65"); 
    } 

爲了測試它。但它不起作用。

+1

看看類似的帖子http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time – 2013-03-12 12:57:17

+0

什麼不工作? – 2013-03-12 13:04:23

回答

0

您可以採用多線程方法。有一個線程只關心紅色鍵,另一個線程只關心藍色。如果您在共享變量上使用同步,它們各自獨立行動,不應互相干擾。