开发者

JTree object casting

I have a number of objects (containing various unique strings + variables) that I wish to display using a JTree. So far I have written code which sets up the tree fine.

for(myClass Item : objectArray){
     ...
     DefaultMutableTreeNode newC开发者_StackOverflow社区hild = new DefaultMutableTreeNode(Item);
     parentNode.add(newChild)
     ...
 }

I have then implemented the toString() method in myClass with an identifier of the object. So for example, my JTree looks like this:

    Root node
       + object1
       + object2
       + object3

Adding a listener, I want to be able to select the required object using the GUI, access it's method and display the object's member variables. However, I'm having trouble retrieving the object. In particular this line:

 myClass selectedObject = (myClass) jTree.getLastSelectedPathComponent()

which gives the following run time error:

   javax.swing.tree.DefaultMutableTreeNode cannot be cast to myClass

Is there not a way to undo the original cast? surely casting to a Jtree node just wraps the object up with extra methods and variables? I'm not sure what to do.


I think you want the getUserObject() from the DefaultMutableTreeNode. Then you can cast it to your class.


Try

DefaultMutableTreeNode node = (DefaultMutableTreeNode) 
                              jTree.getLastSelectedPathComponent();

if (node != null)
{
     myClass selectedObject  = (myClass) node.getUserObject();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜