scala - 如何在方法中分离`react`

时间:2014-11-06 16:19:25

标签: scala

如何在reactions中将KeyPressed or KeyReleasedpanel中的任何panel分开,并将其称为方法,如果需要listenTo(keys, mouse.moves, mouse.clicks) reactions += { case kpr: KeyPressed => if (kpr.key == Key.Up) upPressed = true if (kpr.key == Key.Down) downPressed = true case krl: KeyReleased => if (krl.key == Key.Up) upPressed = false if (krl.key == Key.Down) downPressed = false case me: MouseEntered => requestFocus } ?我有这段代码要分开:

{{1}}

1 个答案:

答案 0 :(得分:1)

我不知道你正在使用哪个API,但我以前使用过java.awt.event.KeyListener API。我想你可能会觉得我的模式很有用。

class InputHandler extends KeyListener {
  val keys = ArrayBuffer[Key]()

  class Key {
    keys += this

    var down = false

    def toggle(pressed: Boolean) {
      down = pressed
    }
  }

  val up = new Key
  val down = new Key
  val garbage = new Key

  def releaseAll() {
    keys.foreach(_.down = false)
  }

  def keyForEvent(e: KeyEvent): Key = e.getKeyCode match {
    case KeyEvent.VK_W => up
    case KeyEvent.VK_UP => up
    case KeyEvent.VK_S => down
    case KeyEvent.VK_DOWN => down
    case _ => garbage
  }

  // for the listener interface equivalent:
  def toggle(e: KeyEvent, pressed: Boolean): Unit = keyForEvent(e).toggle(pressed)
  def keyPressed(e: KeyEvent): Unit = toggle(e, true)
  def keyReleased(e: KeyEvent): Unit = toggle(e, false)
  def keyTyped(e: KeyEvent) {}
}

我有其他状态来维持按键的时间,如果它是一个新的点击等等...你可以建模相同。我认为你不能把关键代码映射到Key实例;你很可能想要使用HashMap,让你的用户更新密钥映射。

编辑:尝试将命令保存为PartialFunction

val commonReactions = {
  case kpr: KeyPressed =>
    if (kpr.key == Key.Up) upPressed = true
    if (kpr.key == Key.Down) downPressed = true
  case krl: KeyReleased =>
    if (krl.key == Key.Up) upPressed = false
    if (krl.key == Key.Down) downPressed = false
  case me: MouseEntered => requestFocus
}

reactions += commonReactions