我在另一个问题(> 如何在Java中同时处理按键?)的注释部分提出了这个问题,并被要求提出一个新问题。
我的问题是,当用户按下按键时,当我创建按键列表ArrayList时,不会通过keyReleased事件足够快地将其删除。我希望运动与“
asdf”和北,东,南,西,东北…等保持一致。
这是我的两个事件的代码:
@Override
public void keyPressed(KeyEvent e) {
if(chatTextField.isFocusOwner() == true){
//do nothing - don't walk
} else {
logger.debug("Key Pressed: " + e.getKeyChar());
lastKey = keysPressed.get(keysPressed.size()-1);
for (String key : keysPressed){
if (!key.contains(String.valueOf(e.getKeyChar())) && !lastKey.contains(String.valueOf(e.getKeyChar()))){
keysPressed.add(String.valueOf(e.getKeyChar()));
System.out.println("ADDED: " + keysPressed);
}
}
String keysList = keysPressed.toString();
if (keysList.contains("w")){
if (keysList.contains("d")){
requestCharacterMove("NorthEast");
} else if(keysList.contains("a")){
requestCharacterMove("NorthWest");
} else{
requestCharacterMove("North");
}
} else if (keysList.contains("s")){
if (keysList.contains("d")){
requestCharacterMove("SouthEast");
} else if(keysList.contains("a")){
requestCharacterMove("SouthWest");
} else{
requestCharacterMove("South");
}
} else if (keysList.contains("d")){
requestCharacterMove("East");
} else if (keysList.contains("a")){
requestCharacterMove("West");
}
}
}
@Override
public void keyReleased(KeyEvent e) {
if(chatTextField.isFocusOwner() == true){
//do nothing - don't walk
} else {
logger.debug("Key Released: " + e.getKeyChar());
for (String key : keysPressed){
if (key.contains(String.valueOf(e.getKeyChar()))){
keysPressed.remove(String.valueOf(e.getKeyChar()));
System.out.println("REMOVED: " + keysPressed);
}
}
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
直到我通过lastKey(String)变量将第二个检查添加到那里,金字塔创建的数量巨大。即使进行第二次检查,列表也会增加,并且几乎总是有两三份重复。因为我的角色笨拙地移动着,所以对此的任何帮助都会很棒。:(
同样,删除重复转换为char,string,arrayList的任何方法也将非常有用,因为我担心我为“简单”使用了太多类型。