Java Swing: Extending TreeNode
I am working on setting up a closed client application. It has a tree in the UI and only exposes a way to get the selected node. It returns a subclass of TreeNode. And there is no way to get a reference to the parent tree. Now I want to expand the selected node to its leaves.
Is there a way to get a reference to the JTree component from the DefaultMutableTreeNode? I am planning to use JTree.expandPath (), but I only have a link to treenode.
I am new to Swing and any suggestions for this would be greatly appreciated.
source to share
In fact, only JTree knows about the state of the extension, there is no such information in TreeNodes. TreeNodes are on the "model" side and do not have a JTree pointer (at least not by default, you can of course make your own with a link, but it breaks the template a bit).
You should reconsider the place where you want to make this extension for the place where you have access to the JTree (provide maybe more details about your context, learn more about what you want to do and in what circumstances) ...
source to share
Looking at the source DefaultMutableTreeNode
, I don't see anything good, but you can try one of the following:
- Expand
DefaultMutableTreeNode
and save the link to your tree - By default, node has the concept of "custom object". You can link to the tree as this object. It is not completely secure, but will probably work. EDIT: Actually, if you look at how the custom object is used (as a textual representation of the tree path and in
toString()
) setting the user object in this way will destroy the intended use of the API. So: unpleasant, but might work.
source to share
A tree node is an element from a tree model. As a consequence, he has nothing to do with the Tree, which is his representation.
What might be interesting to know which object you are in: since you want to respond to a mouse event, I assume you have access to the view layer (at least returning the component that creates the MouseEvent, which should be a JTree). If so, you can get the selected row and call expandPath . Building a TreePath from the DefaultMutableTreeNode remains as an exercise :-)
EDIT From the comments below, let me clarify my answer. You will need to call expandPath using the TreePath created by a simple getPath call in your DefaultMutableTreeNode .
source to share