Search code examples
kotlintornadofx

How to show pojo properties in TornadoFX tableview?


I'm writing a very simple TornadoFX table demo, trying to display the properties of some pojos in a table, but the cells are all empty.

The main code is:

data class User(val id: Int, val name: String)

private val data = listOf(User(111, "AAA"), User(222, "BBB"), User(333, "CCC"), User(444, "DDD")).observable()

class HelloWorld : View() {

    override val root = vbox {
        tableview(data) {
            column("id", User::id.getter)
            column("name", User::name.getter)
        }
    }
}

I use User::id.getter to make it compiling, but the cells are empty.

I did a lot of search, but can't find code to work with current latest tornado (1.7.16)

Here is a complete demo for this: https://github.com/javafx-demos/tornadofx-table-show-pojo-demo


Solution

  • You need to reference the property, not the getter, ie. User::id. To reference immutable properties you need to use the readonlyColumn builder:

    readonlyColumn("id", User::id)
    readonlyColumn("name", User::name)
    

    That said, you really should use JavaFX properties in your domain objects instead. Not doing so in a JavaFX based application just makes everything harder, and you loose out on a lot of benefits, or at the very least you have to jump through hoops.

    Here is the complete application written with observable JavaFX properties. Note that you would then access the idProperty and nameProperty properties instead. With this approach, changes to the underlying data item would automatically be visible in the tableview as well:

    class User(id: Int, name: String) {
        val idProperty = SimpleIntegerProperty(id)
        var id by idProperty
    
        val nameProperty = SimpleStringProperty(name)
        var name by nameProperty
    }
    
    
    private val data = listOf(User(111, "AAA"), User(222, "BBB"), User(333, "CCC"), User(444, "DDD")).observable()
    
    class HelloWorld : View() {
        override val root = vbox {
            tableview(data) {
                column("id", User::idProperty)
                column("name", User::nameProperty)
            }
        }
    }