Home › Core Java Tutorial › Get Jtree Selected Node
By Administrator Updated: Friday, 22 July 2011 15:36
Get JTree selected node
This example gives you a short overview about a single tree selection.
You need first to create your tree, define your model then add a tree selection model :
protected JTree getTree(){
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
doSelectionChange(e);
}
});
return tree;
}
If you are using a single tree selection (TreeSelectionModel.SINGLE_TREE_SELECTION) you can get the selected path by calling the getSelectionPath(). Then �you call getLastPathComponent() to have the leaf.
public void doSelectionChange(TreeSelectionEvent e){
if (tree.isSelectionEmpty()) return;
TreePath path = tree.getSelectionPath();
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
Object userObject = selectedNode.getUserObject();
logger.debug("user object : " + userObject);
...
}
To configure the logging using log4J find
here a sample configuration file
Tags:
tree
,
model
,
selection
,
single
,
selected
,
jtree
,
getselectionpath()
,
call
Add comment