val mutableMap = mutableMapOf<String,String>() class TreeviewDemo:Fragment(){ var tv=TreeView<String>() var nodes=TreeItem<String>() val fname= stringProperty() val content= stringProperty() override val root =vbox { button("load tree") { action { val d=chooseDirectory{} // println(d!!.absoluteFile) runAsync{ nodes=getNodesForDirectory(d!!.absoluteFile) }ui { tv.root=nodes } } } hbox { tv=treeview<String> { root=TreeItem("") bindSelected(fname) selectionModel.selectedItemProperty().addListener { _ -> val fpath=mutableMap.get(selectionModel.selectedItem!!.value) content.value=File(fpath).readText() } } textarea(content) { } } } } //Returns a TreeItem representation of the specified directory tailrec fun getNodesForDirectory(directory: File): TreeItem<String> { val root = TreeItem<String>(directory.getName()) directory.listFiles().forEach { if (it.isDirectory()) { //Then we call the function recursively root.children.add(getNodesForDirectory(it)) } else { root.children.add(TreeItem<String>(it.getName())) } mutableMap.put(it.name,it.absolutePath) } return root }
转载于:https://my.oschina.net/u/3820046/blog/3067988