Scala/Swing - Responding to multiple key events that are happening at the same time

213 views Asked by At

I am trying to figure out how can I make Scala Swing react to multiple key events that are happening at the same time. I know how Swing can detect one key that is pressed, but for example how can it detect if two keys are pressed at the same time? Note: No Java experience

I know that the first event does not work, but I try to represent what I am trying accomplish with it:

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"

        }

Any ideas that might help? Or straight up answers how to do it?

1

There are 1 answers

0
Leero11 On BEST ANSWER

Make a buffer that holds all the keys that are pressed

var pressedKeys = Buffer[Key.Value]()

When key is pressed add the key to the buffer and check if the buffer contains some wanted key values

 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"

Clear the buffer when button released

            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*/