我有一个带有自定义对象和自定义模型的JTree。在某些情况下,我选择一个节点,当发生这种情况时,我用新检索到的数据更新树。当发生这种情况时,我会在树中查找选定的节点,并将其替换为新的(最新的)节点。当我找到它时,我从它的父节点中删除旧节点,将新节点添加到它的位置,并调用nodeChanged(newNode)。树更新正常,新的节点会出现在那里,其中包含更新的内容。
问题是当从这个树更新返回时,选择路径还没有更新,所以当我使用getSelectionPaths()方法时,返回的路径(如果只选择了一个节点)对应于我从树中删除的旧节点。
如何将选择路径更新为新的更新后的模型?
发布于 2012-06-06 04:11:00
您可以创建一个新的TreePath并使用新路径调用setSelectedPath。但是,更好的做法是将节点设置为可变并更新节点,而不是删除节点。这样,树模型不会改变,选择路径也不会改变。
您还需要触发相应的事件(节点已更改,而不是节点已移除/已添加等)。
发布于 2012-06-06 04:35:38
如果能够找到叶的新路径,就可以创建一个TreePath。
我做了一个例子,在JTree中选择一个具有一级节点的叶子:
public JTree fileTree;
public void setJTreePath(String leafName, String nodeName) {
TreeNode root = (TreeNode) fileTree.getModel().getRoot();
TreePath path = new TreePath(root);
int rootChildCount = root.getChildCount();
mainLoop:
for (int i = 0; i < rootChildCount; i++) {
TreeNode child = root.getChildAt(i);
if (child.toString().equals(nodeName)) {
path = path.pathByAddingChild(child);
int ChildCount = child.getChildCount();
for (int j = 0; j < ChildCount; j++) {
TreeNode child2 = child.getChildAt(j);
if (child2.toString().equals(leafName)) {
path = path.pathByAddingChild(child2);
fileTree.setSelectionPath(path);
//I've used a SwingUtilities here, maybe it's not mandatory
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
fileTree.scrollPathToVisible(fileTree.getSelectionPath());
}
});
break mainLoop;
}
}
}
}
}https://stackoverflow.com/questions/10904170
复制相似问题