1

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?

Leero11
  • 365
  • 2
  • 4
  • 17
  • 1
    Possible duplicate of [Swing's KeyListener and multiple keys pressed at the same time](http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time) – Roberto Attias Dec 27 '16 at 20:31

1 Answers1

0

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*/
Leero11
  • 365
  • 2
  • 4
  • 17