java 在 JTree 中获取节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5120165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:32:56  来源:igfitidea点击:

Getting a node in JTree

javaswingjtree

提问by user489041

Simple question. I have a TreePath to a node in my JTree. How can I convert this TreePath to the DefaultMutableTreeNode the TreePath points too?

简单的问题。我的 JTree 中有一个指向节点的 TreePath。如何将此 TreePath 转换为 TreePath 指向的 DefaultMutableTreeNode ?

回答by dontocsata

You should be able to call getLastPathComponenton the TreePathand cast that for a TreeNodeor DefaultMutableTreeNodeand be good to go.

你应该能够调用getLastPathComponentTreePath和演员,其中一个TreeNode还是DefaultMutableTreeNode和好到哪里去。

See: http://download.oracle.com/javase/6/docs/api/javax/swing/tree/TreePath.html#getLastPathComponent%28%29

请参阅:http: //download.oracle.com/javase/6/docs/api/javax/swing/tree/TreePath.html#getLastPathComponent%28%29

回答by Howard

If your treemodel consists of DefaultMutableTreeNodes you may just use node=(DefaultMutableTreeNode)path.getLastPathComponent();

如果您的树模型由 DefaultMutableTreeNodes 组成,您可以使用 node=(DefaultMutableTreeNode)path.getLastPathComponent();

回答by Alobes5

model is a DefaultTreeModel

模型是一个 DefaultTreeModel

private TreePath getTreePath(TreeNode node) {
    TreeNode[] nodes = model.getPathToRoot(node);
    TreePath path = new TreePath(nodes);
    return path;
}