TornadoFX覆盖区域上的layoutChildren

时间:2017-11-25 08:22:02

标签: javafx kotlin tornadofx

我试图将this JavaFX类翻译成TornadoFX。悬停我无法弄清楚TornadoFX应该如何完成protected void layoutChildren()

这是我到目前为止的代码:

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()
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我不确定你翻译TornadoFX的意思,但在Kotlin写layoutChildren看起来像这样:

override fun layoutChildren() {
    layoutInArea(highlight, 0.0, 0.0, width, height, baselineOffset, HPos.CENTER, VPos.CENTER);
}
编辑:您已将代码示例更新为View,因此我认为我理解您现在想要的内容:)

首先,确保View不需要参数,因为这样就无法注入此视图。使用by param()或更好地传递参数,在View的范围内注入ViewModel,并将ViewModel注入到View中。

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

如果你需要创建一个自定义Region,你可以用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
}
相关问题