【问题标题】:Get datepicker date on Kotlin TornadoFX在 Kotlin TornadoFX 上获取日期选择器日期
【发布时间】:2017-12-28 18:36:35
【问题描述】:

我正在为 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!")
                }
            }
        }
    }
}

当按钮被按下时,我想取用户选择的日期。

我该怎么办?

【问题讨论】:

    标签: datepicker kotlin tornadofx


    【解决方案1】:

    一种解决方案是将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!")
                    }
                }
            }
        }
    }
    

    另一种解决方案是在您的类中拥有 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!")
                }
            }
        }      
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多