如何为 javax.swing.Timer 编写 Scala 包装器 [英] How to write a Scala wrapper for javax.swing.Timer
问题描述
我想在 Scala Swing 应用程序中使用计时器.我可以使用Java版本,只是意味着我必须实现ActionListener接口.我宁愿使用 Scala Publishers/Reactors 模型来保持一致性,这样我就可以拥有 listenTo
计时器的东西.
I'd like to use a timer in a Scala Swing application. I can use the Java version, only it means I have to implement the ActionListener interface. I'd rather use the Scala Publishers / Reactors model for consistency, so I can have things that listenTo
the timer.
这是我尝试过的:
class ScalaTimer(time: Int) extends Component {
val t = new javax.swing.Timer(time, new java.awt.event.ActionListener {
def actionPerformed(e: java.awt.event.ActionEvent) {
publish(new scala.swing.event.ActionEvent(this))
}
})
def start() {t.start()}
def stop() {t.stop()}
// etc
}
不起作用,因为 this
指的是 ActionListener 而不是 ScalaTimer 类.
Doesn't work because this
refers to the the ActionListener rather than the ScalaTimer class.
另外,我可能不应该扩展 Component
...我尝试了这个,因为我获得了发布者/反应器功能,但这并没有什么意义.我应该做这样的事情吗?如果是这样,我还需要包含其他特征吗?我如何知道必须实现哪些方法?
Also I probably shouldn't be extending Component
... I tried this because I get the Publisher / Reactor functionality, but it doesn't really make sense. Should I do something like this instead? If so, are there other traits I need to include, and how do I know which methods I have to implement?
class ScalaTimer extends javax.swing.Timer with Publisher {
(我的 IDE 立即标记方法 Timer(Int, ActionListener) 缺少参数",这看起来有点奇怪,因为我没有调用方法.)
(My IDE immediately flags "Missing arguments for method Timer(Int, ActionListener)" which seems a bit weird since I haven't invoked a method.)
推荐答案
执行此操作的规范方法是在要引用的事物(通常是 self
除非已经被占用了):
The canonical way to do this is to introduce an alias at the top of the thing you want to refer to (usually self
unless that's already taken):
class ScalaTimer(time: Int) extends Component {
self =>
val t = ...
publish(new scala.swing.event.ActionEvent(self))
...
这篇关于如何为 javax.swing.Timer 编写 Scala 包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!