• Post Reply Bookmark Topic Watch Topic
  • New Topic

Selecting JTree Nodes�  RSS feed

 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem � I am trying to select a specific tree node in a jtree and display some data that is related to that node.

What I have done-


What I am having trouble with is getting a node from a path. I would like to convert the path
to a "myDataNode" which extend DefaultMutableTreeNode.

Every reference I have found has talked about getting the path to get the node but I can not
find an explanation of how to cross that final step of going from path to node.

Any ideas?
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can print out your selectedPath to see what it is. From the TreePath class api you can use the getLastPathComponent method to get a reference to the node.
 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the 411 Greg but I am still having problems.

I tried printing the selected path before and I get

SelectedPath = [JTree, food]

I am not using a default JTree, I actualy have different nodes so I am not sure why 'food' is coming back as a node.

Additionaly, I extended DefaultMutableTreeNode with a class I called DataNode. If I try the program as you suggested I get no errors. If I do

DataNode node = (DataNode)selectedPath.getLastPathComponent();

I get this error
java.lang.ClassCastException
at gui.PlannerGui.mouseClicked(PlannerGui.java:189)
at java.awt.AWTEventMulticaster.mouseClicked(unknown Source)
...
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rather than extending DefaultMutableTreeNode try letting DataNode stand on its own. Build your JTree with DefaultMutableTreeNodes and use DataNode as the userObject for each of the nodes.
 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I could try that but the purpose of the tree is to give a hierarchical representation of Data contained in a file and to allow the user to manipulate that data via the tree. The DataNodes are simple extended DefaultMutableTreeNodes with getter and setter methods for each field in the file�s records. One node equals a complete record. It seems that I have to use these up front.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!