tornadofx在tableview中使用自定義的TableCell

import javafx.collections.FXCollections
import javafx.scene.control.Button
import javafx.scene.control.TableCell
import tornadofx.*


class LearnApp : App(StudentView::class)

class StudentView : View("Student Info") {
    val warriorModel : StudentModel by inject()
    val persons = FXCollections.observableArrayList<Student>(
        Student(1,"Tyrion Lannister", "M"),
        Student(2,"Ned Stark", "M"),
        Student(3,"Daenerys Targaryen", "F"),
        Student(4,"Arya Stark", "F")
    )
    val Msg= stringProperty()
    override val root = borderpane{
        top=vbox {
            label(Msg)
        }
        center=vbox {
            tableview(persons) {
                isEditable = true
                column("ID", Student::idProperty)
                column("Name", Student::nameProperty).makeEditable()
                column("Gender", Student::genderProperty).useComboBox(FXCollections.observableArrayList("M", "F"))
                column("Action", Student::dummyProperty).setCellFactory { DeleteButton<Student>() }
                bindSelected(warriorModel)
                subscribe<DeleteEvent> { event ->
                    Msg.value="Delete Student: ${items.elementAt(event.index)}"
                    items.removeAt(event.index)
                }
            }
        }
    }

    class DeleteButton<Student>() : TableCell<Student, String?>() {
        internal val btn = Button("Delete")
        override fun updateItem(item: String?, empty: Boolean) {
            super.updateItem(item, empty)
            if (empty) {
                graphic = null
                text = null
            } else {
                btn.setOnAction {
//                    tableView.items.removeAt(index)
                    FX.eventbus.fire(DeleteEvent(index))
                }
                graphic = btn
                text = null
            }
        }
    }
}

class Student(id: Int, name: String, gender: String) {

    val idProperty = intProperty(id)
    var id by idProperty

    val nameProperty = stringProperty(name)
    var name by nameProperty

    val genderProperty = stringProperty(gender)
    var gender by genderProperty

    val dummyProperty = stringProperty("")

    override fun toString(): String {
        return "Student(id:${id}, name:${name}, gender:${gender})"
    }
}
class StudentModel : ItemViewModel<Student>() {
    val id = bind { item?.idProperty }
    val name = bind { item?.nameProperty }
    val gender = bind { item?.genderProperty }
}
class DeleteEvent(val index: Int) : FXEvent()
相關文章
相關標籤/搜索