TornadoFX 重写 layoutChildren on Region

TornadoFX overriding layoutChildren on Region

我正在尝试将 this JavaFX class 翻译成 TornadoFX。悬停我无法弄清楚 protected void layoutChildren() 应该如何使用 TornadoFX?

这是我目前的代码:

class ReversiSquare(x: Int, y: Int) : View() {

    var x by property(x)
    fun xProperty() = getProperty(ReversiSquare::y)

    var y by property(y)
    fun yProperty() = getProperty(ReversiSquare::y)

    var highlight: Region by singleAssign()
    var highlightTransition: FadeTransition by singleAssign()

    val model = ReversiModel

    override val root = region {
        region {
            opacity = 0.0
            style = "-fx-border-width: 3; -fx-border-color: dodgerblue"
            highlight = this
        }
        // todo not sure this works with singleAssign
        highlightTransition = FadeTransition(Duration.millis(200.0), highlight).apply {
            fromValue = 0.0
            toValue = 1.0
        }

        styleProperty().bind(Bindings.`when`(model.legalMove(x, y))
                .then("-fx-background-color: derive(dodgerblue, -60%)")
                .otherwise("-fx-background-color: burlywood"))

        val light = Light.Distant().apply {
            azimuth = -135.0
            elevation = 30.0
        }
        effect = Lighting(light)
        setPrefSize(200.0,200.0)
        this += highlight
        addEventHandler(MouseEvent.MOUSE_ENTERED_TARGET) {
            if(model.legalMove(x ,y).get()) {
                with(highlightTransition) {
                    rate =1.0
                    play()
                }
            }
        }
        addEventHandler(MouseEvent.MOUSE_EXITED_TARGET) {
            with(highlightTransition) {
                rate = -1.0
                play()
            }
        }
        onDoubleClick {
            model.play(x, y)
            highlightTransition.rate = -1.0
            highlightTransition.play()
        }
    }
}

我不确定你翻译成 TornadoFX 是什么意思,但是用 Kotlin 编写 layoutChildren 看起来像这样:

override fun layoutChildren() {
    layoutInArea(highlight, 0.0, 0.0, width, height, baselineOffset, HPos.CENTER, VPos.CENTER);
}

编辑:您将代码示例更新为视图,所以我想我现在明白您想要什么了:)

首先,确保视图不需要参数,因为那样将无法注入此视图。使用 by param() 或更好的方式传递参数,在视图范围内注入一个 ViewModel,然后将该 ViewModel 注入到您的视图中。

也许您可以将 x 和 y 作为属性添加到 ReversiModel?

如果您需要创建自定义区域,您可以创建一个匿名内部 class 等价物,用 Java 来说:

class ReversiSquare : View() {
    val model: ReversiModel by inject()

    override val root = object : Region() {
        // ...

        override fun layoutChildren() {
            layoutInArea(highlight, 0.0, 0.0, width, height, baselineOffset, HPos.CENTER, VPos.CENTER);
        }
    }
}

要立即打开此视图,请创建一个新范围并将 ReversiModel 推入其中:

// Create the model, set x, y and other initial state in the model
val model = ReversiModel()
model.x = 42

// Create a new scope and push the ReversiModel into it
val scope = Scope(model)

// Find the ReversiSquare in the new scope
find<ReversiSquare>(scope) {
    // Do something with the sequare, like openWindow() or similar
}