How to write a Tree Selection Listener in Java

A tree component is paired with some other component. When we selects tree nodes, some information shows up in another window.

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.tree.*;

import javax.swing.event.*;

import java.util.*;

import java.lang.reflect.*;

public class ClassBrowserTest

{

public static void main(String aa[])

{

JFrame frame=new ClassBrowserTestFramee();

frame.show();

}

}

class ClassBrowserTestFramee extends JFrame implements ActionListener,TreeSelectionListener/* for tree listener*/

{

public ClassBrowserTestFramee()

{

setTitle("Class Browser Test");

setSize(500,500);

rooot=new DefaultMutableTreeNode(java.lang.Object.class);

modell=new DefaultTreeModel(rooot);

treee=new JTree(modell);

addClass(getClass());//add this class to the tree with some data

//set up selection mode

treee.addTreeSelectionListener(this);//add the listener to the tree

int modee=TreeSelectionModel.SINGLE_TREE_SELECTION;

treee.getSelectionModel().setSelectionMode(modee);

textAreaa=new JTextArea();

JPanel panell=new JPanel();

panell.setLayout(new GridLayout(1,2));

panell.add(new JScrollPane(treee));

panell.add(new JScrollPane(textAreaa));

Container contentPan=getContentPane();

contentPan.add(panell,"Center");

textField=new JTextField();

textField.addActionListener(this);

contentPan.add(textField,"South");

}

public void actionPerformed(ActionEvent acevent)

{

try

{

String texxt=textField.getText();

addClass(Class.forName(texxt));

textField.setText("");

}

catch(ClassNotFoundException ee)

{

Toolkit.getDefaultToolkit().beep();

}

}

//This method is called whenever the user select or deselect tree nodes.

public void valueChanged(TreeSelectionEvent tevent)

{

//update description

TreePath patth=treee.getSelectionPath();

if(patth==null)

return;

DefaultMutableTreeNode selectedNodee=(DefaultMutableTreeNode)patth.getLastPathComponent();

Class cc=(Class)selectedNodee.getUserObject();

String descriptionn=getFieldDescription(cc);

textAreaa.setText(descriptionn);

}

public DefaultMutableTreeNode findUserObject(Object oobjj)/*find the node with a given user object*/

{

Enumeration en=rooot.breadthFirstEnumeration();

while(en.hasMoreElements())

{

DefaultMutableTreeNode nodee=(DefaultMutableTreeNode)en.nextElement();

if(nodee.getUserObject().equals(oobjj))//retrieve the node that was selected

return nodee;

}

return null;

}

public DefaultMutableTreeNode addClass(Class cc)

{       //add a new class to the tree

if(cc.isInterface() || cc.isPrimitive())  //skip non-class types

return null;

//if the class is already in the tree

DefaultMutableTreeNode nodee=findUserObject(cc);

if(nodee!=null)

return nodee;

//check class if isn’t present then first add class parent

Class cs=cc.getSuperclass();

DefaultMutableTreeNode parent;

if(cs==null)

parent=rooot;

else

parent=addClass(cs);

DefaultMutableTreeNode newNode=new DefaultMutableTreeNode(cc);

modell.insertNodeInto(newNode,parent,parent.getChildCount());

TreePath path=new TreePath(modell.getPathToRoot(newNode));//make node visible

treee.makeVisible(path);

return newNode;

}

public static String getFieldDescription(Class cl)

{

//use reflection to find types & names of fields

String rr="";

Field[] fields=cl.getDeclaredFields();

for(int i=0;i<fields.length;i++)

{

Field fi=fields[i];

if((fi.getModifiers() & Modifier.STATIC)!=0)

rr+="static";

rr+=fi.getType().getName()+" ";

rr+=fi.getName()+"\n";

}

return rr;

}

private DefaultMutableTreeNode rooot;

private DefaultTreeModel modell;

private JTree treee;

private JTextField textField;

private JTextArea textAreaa;

}

Tree Selection Listener in Java

Explanation….

In above example when the user selects a class, the instance and static variables of that class are displayed in the text area to the right.

In the frame constructor, we restrict the user to single item selection and add a tree selection listener. When the valueChanged method is called, simply ask the tree for the current selection path.

We call the getFieldDescription method, which uses reflection to assemble a string with all fields of the selected class.Finally , that string is displayed in the text area.

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @