Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a node in JTree

Tags:

java

swing

jtree

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?

like image 904
user489041 Avatar asked Feb 25 '11 16:02

user489041


People also ask

How does JTree work?

JTree delegates the display of its items to Renderers. By default, a renderer is automatically created for a JTree to display all its items. The rendering is represented by an interface called TreeCellRenderer. The Swing API provides a default implementation of this interface known as DefaultTreeCellRenderer.

What is JTree swing?

JTree is a concept used in Java swing methodology. It is used to display hierarchical data which is in a particular order. It also has a root node which is the most important node in the Java framework. Also, the Jtree concept is used in programming languages wherever a hierarchy of data has to be displayed.


3 Answers

You should be able to call getLastPathComponent on the TreePath and cast that for a TreeNode or DefaultMutableTreeNode and be good to go.

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

like image 106
dontocsata Avatar answered Nov 05 '22 12:11

dontocsata


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

like image 7
Howard Avatar answered Nov 05 '22 10:11

Howard


model is a DefaultTreeModel

private TreePath getTreePath(TreeNode node) {
    TreeNode[] nodes = model.getPathToRoot(node);
    TreePath path = new TreePath(nodes);
    return path;
}
like image 2
Alobes5 Avatar answered Nov 05 '22 11:11

Alobes5