我正在用TornadoFX做第一次实验,遇到了一个我不明白的问题。
我有一个对象Wind
:
enum class Direction(val displayName: String, val abbrevation: String, val deltaX: Int, val deltaY: Int) {
NORTH("Észak", "É", 0, -1),
NORTH_EAST("Északkelet", "ÉK", 1, -1),
EAST("Kelet", "K", 1, 0),
SOUTH_EAST("Délkelet", "DK", 1, 1),
SOUTH("Dél", "D", 0, 1),
SOUTH_WEST("Délnyugat", "DNy", -1, 1),
WEST("Nyugat", "Ny", -1, 0),
NORTH_WEST("Északnyugat", "ÉNy", -1, -1);
val diagonal: Boolean = deltaX != 0 && deltaY != 0
val degree: Double = ordinal * 45.0
fun turnClockwise(eighth: Int = 1) = values()[(ordinal + eighth) umod 8]
fun turnCounterClockwise(eighth: Int = 1) = values()[(ordinal - eighth) umod 8]
fun turn(eighth: Int = 1) = if (eighth < 0) turnCounterClockwise(eighth.absoluteValue) else turnClockwise(eighth)
infix operator fun plus(eighth: Int) = turn(eighth)
infix operator fun minus(eighth: Int) = turn(-eighth)
infix operator fun minus(other: Direction) = (ordinal - other.ordinal) umod 8
}
object Wind {
val directionProperty = SimpleObjectProperty<Direction>(Direction.NORTH)
var direction: Direction
get() = directionProperty.value
set(value) {
println("SET WIND: $value")
directionProperty.value = value
}
}
我想将旋转变换绑定到风向设置。
当我使用旧的JavaFX样式时,它会起作用:
rot.angleProperty().bind(
createDoubleBinding(
Callable {
println("Direction: ${Wind.direction}");
Wind.directionProperty.value.degree * 45
},
Wind.directionProperty))
当我尝试使用更优雅的Kotlin风格的版本时,它没有绑定:
rot.angleProperty().doubleBinding(rot.angleProperty() ) {
println("Direction: ${Wind.direction}")
Wind.directionProperty.value.degree * 45
}
我错过了什么吗?
答案 0 :(得分:1)
doubleBinding()
函数会创建一个Binding
,但不会将其绑定到任何内容。
实际上,我们有两种创建此绑定的方法:
doubleBinding(someProperty) { ... }
。对属性(this)进行操作,希望您返回Double。它不能为空。
someProperty.doubleBinding() { ... }
将该值作为参数接收,并希望您返回Double。该参数可以为空,因此您需要考虑这一点
这给您两个选择:
rot.angleProperty().bind(doubleBinding(Wind.directionProperty) {
value.degree * 45
})
或
rot.angleProperty().bind(Wind.directionProperty.doubleBinding {
it?.degree ?: 0.0 * 45
})
您选择的哪个主要取决于口味,尽管在某些情况下,一个会比另一个更自然。