我想在Scala Swing应用程序中使用计时器。我可以使用Java版本,但这意味着我必须实现ActionListener接口。为了保持一致性,我更喜欢使用Scala Publisher/Reactor模型,这样我就可以拥有listenTo计时器的东西。
这是我尝试过的:
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类。
另外,我可能不应该扩展Component……我尝试这样做是因为我获得了Publisher / Reactor功能,但它并没有真正的意义。我应该做这样的事情吗?如果是这样,我是否还需要包含其他特性,以及如何知道必须实现哪些方法?
class ScalaTimer extends javax.swing.Timer with Publisher {(我的集成开发环境立即标记“方法计时器(Int,ActionListener)的缺失参数”,这看起来有点奇怪,因为我还没有调用方法。)
发布于 2011-07-26 14:17:27
执行此操作的规范方法是在您想要引用的对象的顶部引入别名(通常是self,除非已经使用了):
class ScalaTimer(time: Int) extends Component {
self =>
val t = ...
publish(new scala.swing.event.ActionEvent(self))
...发布于 2011-07-26 14:00:11
不起作用,因为它引用的是ActionListener而不是ScalaTimer类。
汤姆是对的:你可以使用ScalaTimer.this。
(我的集成开发环境会立即标记“方法
Timer(Int, ActionListener)的参数缺失”,这看起来有点奇怪,因为我还没有调用方法。)
Timer(Int, ActionListener)是您已经调用的Timer的构造函数。您需要编写extends javax.swing.Timer(constructor_args)。当然,构造函数参数可能取决于ScalaTimer的构造函数参数。
发布于 2011-07-26 13:46:16
您将能够在Java语言中实现这一点: ScalaTimer.this
在Scala中可能也是如此
https://stackoverflow.com/questions/6825729
复制相似问题