TornadoFX - 使用 ContextMenu 右键单击​​选项删除项目

TornadoFX - remove item with ContextMenu right click option

所以我有一个 table 视图,显示 observedArrayList 个帐户 Account(name, login, pass),这些是数据 类。当我右键单击一个单元格时,会弹出一个删除选项。我想要做的是从 observedArrayList

中删除 Account

只是我找不到任何方法来做到这一点。我没有使用 JavaFX 或 TornadoFX 的经验,我也无法在 google 或 TornadoFX 指南和文档中找到答案。

这是我的代码:

class ToolView : View() {
    override val root = VBox()


    companion object handler {

        //val account1 = Account("Google", "martvdham@gmail.com", "kkk")
        //val account2 = Account("Google", "martvdham@gmail.com", "Password")
        var accounts = FXCollections.observableArrayList<Account>(

        )
        var gson = GsonBuilder().setPrettyPrinting().create()
        val ggson = Gson()

        fun writeData(){
            FileWriter("accounts.json").use {
                ggson.toJson(accounts, it)
            }
        }

        fun readData(){
            accounts.clear()
            FileReader("accounts.json").use{
                var account = gson.fromJson(it, Array<Account>::class.java)
                if(account == null){return}
                for(i in account){
                    accounts.add(i)
                }
            }

        }
    }


    init {
        readData()
        borderpane {
            center {
                tableview<Account>{
                    items = accounts

                    column("Name", Account::name)
                    column("Login", Account::login)
                    column("Password", Account::password)

                    contextMenu = ContextMenu().apply{
                        menuitem("Delete"){
                            selectedItem?.apply{// HERE IS WHERE THE ITEM DELETE CODE SHOULD BE}
                        }
                    }
                }
            }
            bottom{
                button("Add account").setOnAction{
                    replaceWith(AddView::class, ViewTransition.SlideIn)
                }
            }
        }
    }
}

谢谢!

selectedItem 是您拥有的物品 selected/rightclicked。 然后你可以使用 arraylist.remove(selectedItem)

为了澄清@Martacus 的回答,在您的情况下,您只需将 // HERE IS WHERE THE ITEM DELETE CODE SHOULD BE 替换为 accounts.remove(this) 即可。

您也可以替换行

selectedItem?.apply{ accounts.remove(this) }

selectedItem?.let{ accounts.remove(it) }

根据我的经验,当您只是使用值而不是设置接收器时,letapply 更常见。


请注意,如果 accounts 列表是异步构造并复制进来的,则过程会有所不同,这是 asyncItems { accounts } 的默认行为。