posted 18 years ago
Hi All,
This is a class which extends JTree class forms a Tree displaying employee information.Listener is written which should find the list of selected Employee nodes of tree component.
The method valueChanged() of treeListener is getting called twice for every node selected. Please find the code.
Is there any alternative to find the list of selected nodes when they are selected using mouse or shift key.
Even I am facing this in case of row selection of JTable.The listener method is called twice. Could you please let me know your views and any tutorials or examples codes for handling such cases.
public class TestingTreeModel extends JTree {
//public vector myMOType;
public TestingTreeModel() {
super();
}
public void setData(ArrayList testVOs) {
// set the option of selecting multiple nodes
this.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
this.setRootVisible(false);
setModel(rootTreeNode, testVOs);
// DefaultTreeModel is used.
this.setModel(new DefaultTreeModel(rootTreeNode));
// Listener for selected nodes..
MyTreeSelectionListener myTreeListener = new MyTreeSelectionListener();
this.addTreeSelectionListener(myTreeListener);
}
// which sets the data.
public void setModel(DefaultMutableTreeNode rootNode, ArrayList empVOs) {
if empVOs!= null && empVOs.size() > 0) {
Iterator empItr = empVOs.iterator();
while (neItr.hasNext()) {
Employee empVO = (Employee) empItr.next();
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(empVO.getName());
rootNode.add(node);
}
}
}
// Listener
public class MyTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent evt) {
// Get all nodes whose selection status has changed
System.err.println("Listener is called here check how many times");
getSelectedNodes(evt);
}
}
private void getSelectedNodes(TreeSelectionEvent evt) {
System.err.println("came inside getSelectedNodes");
TreePath[] paths = evt.getPaths();
// Iterate through all affected nodes
System.err.println(" Length is " + paths.length);
for (int i = 0; i < paths.length; i++) {
TreePath tp = paths;
Object[] o = tp.getPath();
for (int j = 0; j < o.length; j++) {
System.out.println(
"Class: " + o[j].getClass() + "; value: " + o[j]);
if (o[j] instanceof DefaultMutableTreeNode) {
Object uo = ((DefaultMutableTreeNode) o[j]).getUserObject();
if (uo != null) {
System.out.println(
"\tUser object class: "
+ uo.getClass()
+ "; value: "
+ uo);
}
}
}
}
}
private ArrayList empIDList = new ArrayList();
private DefaultMutableTreeNode rootTreeNode = null;
}