我正在为 Kotlin 学习 TornadoFX 的基础知识。
我有这个代码:
class MainView : View() {
override val root = vbox()
init {
with(root) {
datepicker {
value = LocalDate.now()
}
button("Choose date") {
textFill = Color.GREEN
action {
println("Button pressed!")
}
}
}
}
}
按下按钮时,我想采用用户选择的日期。
我能怎么做?
最佳答案
一种解决方案是使用 LocalDate
绑定(bind)到 DatePicker
的属性, 像这样:
class MainView : View() {
private val dateProperty = SimpleObjectProperty<LocalDate>()
override val root = vbox()
init {
with(root) {
datepicker(dateProperty) {
value = LocalDate.now()
}
button("Choose date") {
textFill = Color.GREEN
action {
val dateValue = dateProperty.value
println("Button pressed!")
}
}
}
}
}
另一种解决方案是使用
DatePicker
类中的实例,然后从中获取值,如下所示:class MainView : View() {
private var datePicker : DatePicker by singleAssign()
override val root = vbox()
init {
with(root) {
datePicker = datepicker {
value = LocalDate.now()
}
button("Choose date") {
textFill = Color.GREEN
action {
val dateValue = datePicker.value
println("Button pressed!")
}
}
}
}
}
此外,您可以实现
ViewModel
,要分离 UI 和逻辑,请参阅:Editing Models and Validation此外,您的代码风格可以改进:您可以直接使用 VBox,如下所示:
class MainView : View() {
override val root = vbox {
datepicker {
value = LocalDate.now()
}
button("Choose date") {
textFill = Color.GREEN
action {
println("Button pressed!")
}
}
}
}
关于datepicker - 在 Kotlin TornadoFX 上获取日期选择器日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48004940/