简体   繁体   English

选择ComboBox中的项目时调用功能TornadoFX

[英]Invoke Function When Item in ComboBox is Selected TornadoFX

How would I setup a combo box in tornadofx so that a function is called when an item from its drop-down is selected, and the text of the selected item is passed into that function as an argument. 我如何在tornadofx中设置一个组合框,以便在从下拉菜单中选择一个项目时调用该函数,并将所选项目的文本作为参数传递给该函数。

For instance, if I had an array containing names of cities, and those names are set as the items in the combo box: 例如,如果我有一个包含城市名称的数组,并且这些名称被设置为组合框中的项目:

val cities = FXCollections.observableArrayList("Dallas", "New York", "Sacramento")

combobox<String>
{
    items = cities
    //when item is selected from list perform some function on the name of the city selected
}

How could I, for instance, invoke a function when one of the items is clicked that prints the city name to the console? 例如,当单击其中一项将城市名称打印到控制台时,如何调用一个函数?

You can add an onChange listener to the itemProperty of the ComboBox , or you could bind the ComboBox to an external property and listen for changes to that instead. 您可以将onChange侦听器添加到ComboBoxitemProperty ,也可以将ComboBox绑定到外部属性,然后侦听对该属性的更改。 Here is a complete example View with a Form: 这是带有表单的完整示例视图:

class MyView : View() {
    val cities = FXCollections.observableArrayList("Dallas", "New York", "Sacramento")
    val selectedCity = SimpleStringProperty()

    override val root = form {
        fieldset {
            field("City") {
                combobox(selectedCity, cities)
            }
        }
    }

    init {
        selectedCity.onChange {
            println("City changed to: $it")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM