Thursday May 10



User Menu


AddThis Social Bookmark Button

Get JTree selected node

PDF Print E-mail
Wednesday, 20 July 2011 13:22
AddThis Social Bookmark Button

Swing JTree selection example

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 :

Tree selection listener

    protected JTree getTree(){
	tree.addTreeSelectionListener(new TreeSelectionListener() {
	    public void valueChanged(TreeSelectionEvent 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.

get JTree selection user object

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

Security code