0

So I have a table view that displays an observedArrayList of AccountsAccount(name, login, pass), those are data classes. When I right click a cell there pops an option of delete. What I want to do is delete that Account from the observedArrayList

Only I can not find any way to do this. I am not experienced with JavaFX or TornadoFX and I also can't find the answer with google or in the TornadoFX guides and docs.

This is my code:

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)
                }
            }
        }
    }
}

Thanks!

4

2 回答 2

2

为了澄清@Martacus 的答案,在您的情况下,您只需要替换// HERE IS WHERE THE ITEM DELETE CODE SHOULD BEaccounts.remove(this)并且您正在开展业务。

您也可以替换该行

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

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

根据我的经验,这比仅使用值而不是设置接收器时let更常见。apply


accounts请注意,如果列表是异步构建并复制进来的,则该过程将有所不同,这是asyncItems { accounts }.

于 2016-08-08T16:13:54.977 回答
1

selectedItem是您选择/右键单击的项目。然后你可以使用arraylist.remove(selectedItem)

于 2016-08-08T10:14:57.177 回答