响应 scala 中的关键事件
我正在尝试一些 Scala gui 编程(我在 scala 中的第一个项目,所以我想我应该从简单的东西开始)。但我似乎陷入了一些看起来应该相对微不足道的事情。我有一个扩展 scala.swing.MainFrame 的类,我想在该窗口具有焦点时检测用户何时按下某个键。有趣的是,我似乎无法找到任何方法来触发该事件。
我在这里找到了其他人如何解决该问题的示例:http://houseofmirrors.googlecode.com/svn/trunk/src/src/main/scala/HouseGui.scala,但他们似乎已恢复使用 Java Swing API,这有点令人失望。有谁知道是否有更惯用的拦截事件的方法?
I'm experimenting with a bit of Scala gui programming (my first project in scala, so I thought I'd start with something simple). But I seem to have got stuck at something that seems like it should be relatively trivial. I have a class that extends scala.swing.MainFrame, and I'd like to detect when a user presses a key when that window has focus. Funny thing is I don't seem to be able to find any way to get that event to fire.
I found an example of how someone else had got around the problem here: http://houseofmirrors.googlecode.com/svn/trunk/src/src/main/scala/HouseGui.scala but they seem to have reverted to using the Java Swing API, which is a little disappointing. Does anyone know if there's a more idiomatic way of intercepting events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这似乎适用于 Scala 2.9
This seems to work with Scala 2.9
除了监听
this.keys
之外,您还应该在组件上调用 requestFocus 或设置 focusable=true(如果它是 Panel 或派生类)。In addition to listening to
this.keys
you should also call requestFocus on the component or set focusable=true, if it is Panel or derived class.我希望您需要监听
this.keys
(其中this
是接收键盘事件的 GUI 元素)。请参阅有关鼠标事件的等效问题。I expect you need to listen to
this.keys
(wherethis
is the element of the GUI receiving the keyboard events). See the equivalent question about mouse event.我的解决方案要求我执行以下操作:
这似乎只有在没有按钮对象附加到该组件或其任何子组件时才有效。
My solution for this required me to do the following:
This only seemed to work though if there were no button objects attached to this component, or any of it's children.
所有组件都具有发布这些事件的
key
,而不是退回到 java 事件(所以MainFrame
没有)。不确定最好的解决方案是什么,但总是可以将框架中的所有内容包装在Component
内并监听其keys
。Rather than falling back to java events all components have
keys
that publishes these events (soMainFrame
does not). Not sure what the best solution is but it's always possible to wrap everything in the frame inside aComponent
and listen to itskeys
.