Views
8 months ago

tornadofx-guide

11. Editing Models and

11. Editing Models and Validation Editing Models and Validation TornadoFX doesn't force any particular architectural pattern on you as a developer, and it works equally well with both MVC, MVP, and their derivatives. To help with implementing these patterns TornadoFX provides a tool called ViewModel that helps cleanly separate your UI and business logic, giving you features like rollback/commit and dirty state checking. These patterns are hard or cumbersome to implement manually, so it is advised to leverage the ViewModel and ViewModelItem when it is needed. Typically you will use the ItemViewModel when you are creating a facade in front of a single object, and a ViewModel for more complex situations. A Typical Use Case Say you have a given domain type Person . We allow its two properties to be nullable so they can be inputted later by the user. import tornadofx.* class Person(name: String? = null, title: String? = null) { val nameProperty = SimpleStringProperty(this, "name", name) var name by nameProperty } val titleProperty = SimpleStringProperty(this, "title", title) var title by titleProperty (Notice the import, you need to import at least tornadofx.getValue and tornadofx.setValue for the by delegate to work)*[]: Consider a Master/Detail view where you have a TableView displaying a list of people, and a Form where the currently selected person's information can be edited. Before we get into the ViewModel , we will create a version of this View without using the ViewModel . 152

11. Editing Models and Validation Figure 11.1 Below is code for our first attempt in building this, and it has a number of problems we will address. import javafx.scene.control.TableView import javafx.scene.control.TextField import javafx.scene.layout.BorderPane import tornadofx.* class Person(name: String? = null, title: String? = null) { val nameProperty = SimpleStringProperty(this, "name", name) var name by nameProperty } val titleProperty = SimpleStringProperty(this, "title", title) var title by titleProperty class PersonEditor : View("Person Editor") { override val root = BorderPane() var nameField : TextField by singleAssign() var titleField : TextField by singleAssign() var personTable : TableView by singleAssign() // Some fake data for our table val persons = listOf(Person("John", "Manager"), Person("Jay", "Worker bee")).obser 153

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