1

我有几个节点的树,还为此创建了一个树侦听器,现在我需要在单击它时获取特定的节点路径,我已经尝试过这段代码但没有得到确切的输出有人可以帮助我吗?

public class FTListener implements TreeSelectionListener {


    @Override
    public void valueChanged(TreeSelectionEvent e) {
        TreePath[] tree=new TreePath[e.getNewLeadSelectionPath().getPathCount()];
        int i=0;

        tree=e.getPaths();

        for(TreePath tr:tree){
            System.out.println(tree[i]);
        i++;}

        //getPath() returns the array elements so i'm here using 
    //for loop for printing each elements.

这是输出

[/Desktop, /home/user/Desktop, /home/user/Desktop/1302677132563_USER_MANUAL_SMS_BANKING.pdf]
[/Desktop, /home/user/Desktop, /home/user/Desktop/Lab090C .java~]
4

1 回答 1

1

做这个

public void valueChanged(TreeSelectionEvent e) {

    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                       tree.getLastSelectedPathComponent();

    if (node == null) {
    //since Nothing is selected.     
     return;
    }

    Object nodeObject = node.getUserObject();
    System.out.println("Selected node : " + nodeObject);
}

如果您只想单选,请添加此选项

tree.getSelectionModel().setSelectionMode
        (TreeSelectionModel.SINGLE_TREE_SELECTION);
于 2012-11-30T10:08:25.103 回答