Ta-Da
class Point(val x: Int,val y: Int) //You can put properties in constructor
class PointConverter: StringConverter<Point?>() {
override fun fromString(string: String?): Point? {
if(string.isNullOrBlank()) return null //Empty strings aren't valid
val xy = string.split(",",limit = 2) //Only using 2 coordinate values so max is 2
if(xy.size < 2) return null //Min values is also 2
val x = xy[0].trim().toIntOrNull() //Trim white space,try to convert
val y = xy[1].trim().toIntOrNull()
return if(x == null || y == null) null //If either conversion fails,count as invalid
else Point(x,y)
}
override fun toString(point: Point?): String {
return "${point?.x},${point?.y}"
}
}
class MainView : View("Hello TornadoFX") {
val point = Point(5,6) //Probably doesn't need to be its own member
val pointProperty = SimpleObjectProperty<Point>(point)
val pc = PointConverter()
override val root = vbox {
label(pointProperty,converter = pc) //Avoid extra properties,put converter in construction
textfield(pointProperty,pc)
}
}
我仅通过返回null来对转换器进行编辑,以对“帐户”进行无效输入。这只是一个简单的创可贴解决方案,它不会强制输入正确的内容,但是会拒绝在属性中放置错误的值。
,
这可以更干净地完成。我敢打赌,这种额外财产周围有办法。该示例非常脆弱,因为为了保持简单而不进行输入检查。但这可以证明解决方案:
class Point(x: Int,y: Int) {
val x: Int = x
val y: Int = y
}
class PointConverter: StringConverter<Point?>() {
override fun fromString(string: String?): Point? {
val xy = string?.split(",")
return Point(xy[0].toInt(),xy[1].toInt())
}
override fun toString(point: Point?): String {
return "${point?.x},6)
val pointProperty = SimpleObjectProperty<Point>(point)
val pointDisplayProperty = SimpleStringProperty()
val pointStringProperty = SimpleStringProperty()
val pc = PointConverter()
init {
pointDisplayProperty.set(pc.toString(pointProperty.value))
pointStringProperty.set(pc.toString(pointProperty.value))
pointStringProperty.addListener { observable,oldValue,newValue ->
pointProperty.set(pc.fromString(newValue))
pointDisplayProperty.set(pc.toString(pointProperty.value))
}
}
override val root = vbox {
label(pointDisplayProperty)
textfield(pointStringProperty)
}
}
本文链接:https://www.f2er.com/3164018.html