kotlin - 如何将自定义属性双向绑定到文本字段?
问题描述
我有一个想要在文本字段中显示的复杂对象。这与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?我查看了很多属性和绑定文档,但没有看到任何明显的东西。
解决方案
达达
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 来“解释”无效输入。这只是一个简单的创可贴解决方案,它不会强制执行正确的输入,但它确实拒绝在您的属性中放置错误的值。
推荐阅读
- flutter - Flutter 集成测试:模拟应用程序类值
- javascript - 使用 reduxjs/toolkit 向 createAction 函数添加有效负载
- sharepoint - 在 Microsoft Graph API 中按文件类型或名称过滤
- excel - SQL中等效的Excel合并单元格
- python - Python列表索引中的递归排序超出范围
- ios - 将 SwiftUI View 解散回 UIKit ViewController
- python - 声音播放时如何修复opencv视频冻结几秒钟?
- c# - 如何在运行时更改我的 SQLite 连接字符串?
- c# - 对 UserManager 进行额外的异步调用
分页后 - python - PyTouchBar:没有名为 Foundation 的模块