简体   繁体   中英

Java Swing: Expanding TreeNode

I am working on customizing a closed source client application. It has a tree in the UI and exposed only a method 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 upto its leaves.

Is there any way to get a reference to the JTree component from a DefaultMutableTreeNode? I am planning to use the JTree.expandPath() but I only have the reference to the treenode.

I'm new to Swing and any suggestions to achieve this are welcome.

Actually, only the JTree is aware of the expansion state, there is no such information in the TreeNodes. The TreeNodes are on the "model" side, and have no pointer on the JTree (at least not default ones, you can of course make your own with a reference, but it breaks a bit the pattern).

You should reconsider the place where you want to make this expansion for a place in which you have access to the JTree (provide maybe more details about your context, to know more what you want to do, and in which circumstances).

Looking at the source for DefaultMutableTreeNode , I can't see any nice way to do it, but you could try one of the following:

  • Extend DefaultMutableTreeNode and store the reference to your tree
  • The default node has a concept of a "user object". You could set the reference to the tree as this object. It's completely un-type safe, but would probably work. Actually, looking closer at how user object is used (as a textual representation of the tree path and in toString() ), setting the user object in this way would be massacring the API's intended use. 实际上,仔细查看用户对象的使用方式(作为树路径和toString()的文本表示形式),以这种方式设置用户对象将破坏API的预期用途。 So: nasty, but might work.

The tree node is an element from the tree model. As a consequence, it doesn't have any reference to the Tree that is its view.

What could be interesting is to know in which object you are : since you want to react to a mouse event, I guess you have access to the view layer (at least by getting back the component originating the MouseEvent, which should be the JTree). If so, you can get the selected row and call expandPath . Building the TreePath from the DefaultMutableTreeNode is left as an exercise :-)

EDIT From the below comments, let me clarify my answer. You'll have to call expandPath using a TreePath generated by simply calling getPath on your DefaultMutableTreeNode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM