如何在Scala反应中使用键事件

时间:2012-08-01 20:53:03

标签: scala awt

假设存在“反应”块,例如

this.reactions += {
  case KeyReleased(src, key, mod, _) => {
  // do some stuff
  // but how to consume this KeyEvent??
  }
}

在doint“some stuff”之后我想要使用KeyEvent,但我不知道怎么做。查看Component.scala上的源代码我已经找到了如何构造KeyReleased事件:

object keys extends Publisher {
  peer.addKeyListener(new KeyListener {
    def keyPressed(e: java.awt.event.KeyEvent) { publish(new KeyPressed(e)) }
    def keyReleased(e: java.awt.event.KeyEvent) { publish(new KeyReleased(e)) }
    def keyTyped(e: java.awt.event.KeyEvent) { publish(new KeyTyped(e)) }
  })
}

java.awt.event.KeyEvent用作构造函数参数,但KeyReleased 案例类具有此签名

case class KeyReleased(val source: Component, key: Key.Value, val modifiers: Key.Modifiers, 
                location: Key.Location.Value)
               (val peer: java.awt.event.KeyEvent) extends KeyEvent {
def this(e: java.awt.event.KeyEvent) = 
this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
    Key(e.getKeyCode), e.getModifiersEx, Key.Location(e.getKeyLocation))(e) 
}

因此我无法访问KeyEvent参数。

1 个答案:

答案 0 :(得分:4)

您不必在case语句反应中解压缩KeyReleased事件。只需匹配事件本身就可以调用它上面的消费。

reactions += {
    case e: KeyReleased => {
        println(e.source, e.key, e.modifiers)
        e.consume
    }
}