java JTree节点编辑路径比较始终为true
我已经在一个文件服务器程序上工作了一段时间,到目前为止,我能够避免在这里发布一些帮助信息。但是我找不到关于我的问题的任何东西,我非常困惑
我添加了一个弹出菜单,可以选择创建新的顶级文件夹,它实际上只是创建一个节点,在编辑后将其名称发送到服务器以创建文件夹。虽然我已经让所有的编辑工作正常,上传工作正常,但我遇到了一个问题
当创建文件夹时,我将JTree更改为可编辑,并执行一个while循环,直到该节点不是正在编辑的节点,此时它将从JTree中删除编辑功能
public static void newTopFolder(){
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); //now we have the root
DefaultMutableTreeNode newFolder = new DefaultMutableTreeNode("New Folder");//will change to increment for duplicates
DefaultMutableTreeNode empty = new DefaultMutableTreeNode("< empty >"); //easier way to have empty folder, don't worry about it
tree.setEditable(true); //sets to editable
model.insertNodeInto(newFolder, root, root.getChildCount()); //adds folder to tree
model.insertNodeInto(empty, newFolder, newFolder.getChildCount()); //adds empty to tree, not real file
TreePath nfPath = getPath(newFolder); //so we don't call getPath extra times
tree.startEditingAtPath(nfPath); //automatically selects folder to edit
System.out.println(tree.getEditingPath().toString()+":"+nfPath.toString()+";"); //returns [\user\, New Folder]:[\user\, New Folder]; which shows the two are equal
while(tree.getEditingPath().equals(nfPath)){//when nothing is selected null if nothing is being edited, and path to other objects if selected
}
tree.setEditable(false); //changes to node will have been committed and editing disable
sendFolderToServer(nfPath); //sends folder to server after formatting as a String used in new File(Paths.get(nfPath));
}
不幸的是,while检查tree.getEditingPath().equals(nfPath)
总是返回true
,因此它仍然是可编辑的
但我不明白为什么它仍然是真的,它显然不应该是真的。如果它有帮助/改变任何东西,这是在一个单独的线程中运行的(否则while循环将阻止GUI呈现)
那么我应该/可以做什么,有没有更好的方法,或者至少有一种有效的方法
更新:
虽然我还没有找到解决上述问题的方法,但如果我改为测试tree.isPathSelected(nfPath)
,它可以正常工作,并且之后树被设置为不可编辑
# 1 楼答案
获取编辑路径不会删除正在编辑的路径的变量。。。因此,编辑完成后,最近编辑的路径仍然是正确的路径
相反,使用
tree.isPathSelected(path)
将有效