我现在可以建议的是重用scala.swing
实现Publish/React系统的模式。可以从旧存储库中的scala.swing.Componentscala.swing
中获取一个示例 。
这个想法是为所有需要发布事件的javafx类创建可能最通用的包装器,并将这些类隐式转换为这个包装器。
包装器将定义将事件从javafx侦听器连接到发布/反应系统的逻辑。
示例代码如下所示,并且基于上述scala.swing
代码
package scala.fx.react
object ScalaFxReactive {
/*
* Can't say if Node is the best and only class that should be converted.
* You should make implicit publishers from any fx class that supports the
* addEventHandler(someEventType)
*/
implicit def toPublisher(peer: Node): ScalaFxComponentPublisher = new ScalaFxComponentPublisher(peer)
class ScalaFxComponentPublisher(peer: Component) {
/**
* Contains publishers for various mouse events. They are separated for
* efficiency reasons.
*/
object mouse {
/**
* Publishes clicks, presses and releases.
*/
val clicks: Publisher = new LazyPublisher {
lazy val clicked = new EventHandler[MouseEvent] {
def handle(e: MouseEvent) {
/*
*This is the most critical part: you need
* to check if it's possible to create the swing
* event from an fx event, eventually through an
* implicit conversion
*/
publish(new MouseClicked(e))
}
}
def onFirstSubscribe() = peer.setOnMouseClicked(clicked)
def onLastUnsubscribe() = peer.setOnMouseClicked(null)
/*
* probably better:
* def onLastUnsubscribe() = peer.removeEventHandler(MouseEvent.MOUSE_CLICKED)
*/
}
/**
* Publishes enters, exits, moves, and drags.
*/
val moves: Publisher = new LazyPublisher {
lazy val entered = new EventHandler[MouseEvent] {
def handle(e: MouseEvent) {
publish(new MouseEntered(e))
}
}
lazy val exited = new EventHandler[MouseEvent] {
def handle(e: MouseEvent) {
publish(new MouseExited(e))
}
}
/*
* Need implementation
*/
lazy val moved = new EventHandler[MouseEvent] {
...
}
def onFirstSubscribe() {
peer.setOnMouseEntered(entered)
peer.setOnMouseExited(exited)
...
}
def onLastUnsubscribe() {
peer.setOnMouseEntered(null)
peer.setOnMouseExited(null)
...
}
}
}
}
然后你可以支持在你的组件中做出反应,就像你做的那样scala.swing
class MyComponent {
import scala.fx.react.ScalaFxReactive._
listenTo(node)
reactions += {
...
}
}
代码将被视为粗略的草图,不会按原样编译。它指向了一个可能的方向,但对于像您一样需要逐步将遗留scala.swing
应用程序连接到库的人来说,完整的解决方案可能是一个足够有趣的javafx
库。