0

我试图将这个JavaFX 类翻译成 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()
        }
    }
}
4

1 回答 1

1

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

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

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

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

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

如果你需要创建一个自定义区域,你可以创建一个匿名内部类等价物,用 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
}
于 2017-11-25T09:11:31.317 回答