我试图弄清楚如何让 Scala Swing 对同时发生的多个关键事件使用react。我知道 Swing 如何检测按下的一个键,但例如它如何检测是否同时按下两个键?注意:没有 Java 经验
我知道第一个事件不起作用,但我尝试表示我试图用它完成的任务:
reactions += {
//case KeyPressed(_, Key.Space && Key.Up, _, _)
//label.text = "Space and Up are down"
case KeyPressed(_, Key.Space, _, _) =>
label.text = "Space is down"
case KeyPressed(_, Key.Up, _, _) =>
label.text = "Up is down"
}
有什么想法可能有帮助吗?或者直接回答如何做?
最佳答案
创建一个缓冲区来保存所有按下的键
var pressedKeys = Buffer[Key.Value]()
当按下按键时,将按键添加到缓冲区并检查缓冲区是否包含一些想要的键值
reactions += {
case KeyPressed(_, key, _, _) =>
pressedKeys += key
if(pressedKeys contains Key.Space){ //Do if Space
label.text = "Space is down"
if(pressedKeys contains Key.Up) //Do if Space and Up
label.text = "Space and Up are down"
}else if(pressedKeys contains Key.Up)//Do if Up
label.text = "Up is down"
释放按钮时清除缓冲区
case KeyReleased(_, key, _, _) =>
pressedKeys = Buffer[Key.Value]()
/* I tried only to remove the last key with
* pressedKeys -= key, but ended up working
*badly, because in many occasions the program
*did not remove the key*/
关于java - Scala/Swing - 响应同时发生的多个关键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41350800/