Views
1 week ago

tornadofx-guide

5. Data Controls

5. Data Controls Traditionally in JavaFX, populating these elements is rather cumbersome and verbose. Fortunately TornadoFX makes it relatively simple. Say you have a simple type Person and an ObservableList containing several instances. data class Person(val name: String, val department: String) val persons = listOf( Person("Mary Hanes","Marketing"), Person("Steve Folley","Customer Service"), Person("John Ramsy","IT Help Desk"), Person("Erlick Foyes","Customer Service"), Person("Erin James","Marketing"), Person("Jacob Mays","IT Help Desk"), Person("Larry Cable","Customer Service") ) Creating a TreeView with the treeview() builder can be done functionally Figure 5.7). // Create Person objects for the departments // with the department name as Person.name val departments = persons .map { it.department } .distinct().map { Person(it, "") } treeview { // Create root item root = TreeItem(Person("Departments", "")) // Make sure the text in each TreeItem is the name of the Person cellFormat { text = it.name } // Generate items. Children of the root item will contain departments populate { parent -> if (parent == root) departments else persons.filter { it.department == parent. value.name } } } Figure 5.7 62

5. Data Controls Let's break this down: val departments = persons .map { it.department } .distinct().map { Person(it, "") } First we gather a distinct list of all the departments derived from the persons list. But then we put each department String in a Person object since the TreeView only accepts Person elements. While this is not very intuitive, this is the constraint and design of TreeView . We must make each department a Person for it to be accepted. treeview { // Create root item root = TreeItem(Person("Departments", "")) 63

GUIDE
GUIDE
Guide
Guide
Guide
GUIDE
GUIDE
Guide
GUIDE
GUIDE
GUIDE
GUIDE
GUIDE
Guide