JTree : Getting the parent of a selected node.
I have a JTree that could be visualised as follows :
root
|-- PersonA
||-- AddrA1
||-- AddrA2
|-- PersonB
|-- AddrB1
|-- AddrB2
|-- AddrB3
My tree model is identical as the one that we could find from Swing tutorial,
GenealogyModel.java
I would like to know how to find the parent of a selected node. If a user
select, say, AddrA2, the parent
is PersonA. If AddrB3, it's PersonB.
I tried to use the following code :
tree.addTreeSelectionListener(new TreeSelectionListener(){
publicvoid valueChanged(TreeSelectionEvent e){
Object o = tree.getLastSelectedPathComponent();
if (oinstanceof Address){
// Find the parent of the selected Address
TreePath path = tree.getSelectionPath();
log.info("==> Path is " + path.toString());
DefaultMutableTreeNode node = (DefaultMutableTreeNode)o;
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
Person p = (Parent)parent.getUserObject();
}
}
});
but it throws an ClassCastException, saying that Address class cannot be cast to DefaultMutableTreeNode.
Anyone knows how to get the parent of a selectec node ?
Thanks for any help/suggestions.

