在 Kotlin TornadoFX 上获取日期选择器日期
Get datepicker date on Kotlin TornadoFX
我正在学习适用于 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
属性 绑定到 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!")
}
}
}
}
}
另一种解决方案是在 class 中包含 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!")
}
}
}
}
我正在学习适用于 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
属性 绑定到 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!")
}
}
}
}
}
另一种解决方案是在 class 中包含 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!")
}
}
}
}