2

假设有一个“反应”块,例如

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

在点“一些东西”之后,我想使用 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 参数。

4

1 回答 1

4

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

reactions += {
    case e: KeyReleased => {
        println(e.source, e.key, e.modifiers)
        e.consume
    }
}
于 2012-08-02T12:23:05.173 回答