How do I know when a treenode of JTree has/lost focus?

Sandip Chitale

First of all one needs to define what it means by the treenode has focus. That is because treenode itself is not a component. It is simply painted using a rubberstamp of TreeCellRenderer. The synthetic focus of a treenode is defined as follows as is evident from the following code snippet from javax.swing.plaf.basic.BasicTextUI source code -


 	int leadIndex;

 	if(tree.hasFocus()) {
 	    leadIndex = getLeadSelectionRow();
 	}
 	else
 	    leadIndex = -1;

 	Component component;

 	component = currentCellRenderer.getTreeCellRendererComponent
 	              (tree,
                       path.getLastPathComponent(),
 		       tree.isRowSelected(row), isExpanded,
                       isLeaf, row,
                        /************* IMPORTANT *************/
 		       (leadIndex == row));
                        /************* IMPORTANT *************/

Thus if the tree has focus and the lead selection row is same as the row of the treenode in question then one can deduce that the treenode has the focus.

Thus by monitoring the changes in focus of JTree itself (using addFocusListener(FocusListener)) and the selection changes (using addTreeSelectionListener(TreeSelectionListener)) one can monitor the focus chages.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact