首页 > 解决方案 > 如何将自定义属性双向绑定到文本字段?

问题描述

我有一个想要在文本字段中显示的复杂对象。这与stringBinding. 但我不知道如何使它成为双向以便文本字段可编辑。

package com.example.demo.view

import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import tornadofx.*

class MainView : View("Hello TornadoFX") {
    val complexThing: Int = 1
    val complexProperty = SimpleObjectProperty<Int>(complexThing)

    val complexString = complexProperty.stringBinding { complexProperty.toString() }

    val plainString = "asdf"
    val plainProperty = SimpleStringProperty(plainString)

    override val root = vbox {
        textfield(complexString)
        label(plainProperty)
        textfield(plainProperty)
    }
}

当我运行它时,它plainString是可编辑的,并且我看到标签发生了变化,因为编辑将返回到属性中。

如何编写自定义处理程序或我需要使用什么类来读取写入 stringBinding?我查看了很多属性和绑定文档,但没有看到任何明显的东西。

标签: kotlintornadofx

解决方案


达达

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 来“解释”无效输入。这只是一个简单的创可贴解决方案,它不会强制执行正确的输入,但它确实拒绝在您的属性中放置错误的值。


推荐阅读