我有几个节点的树,并为此创建一个树监听器,现在我需要在单击时获取特定的节点路径, 我已经尝试过这段代码,但没有得到任何人帮助我的确切输出?
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~]
答案 0 :(得分: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);