java JTree:如何获取选定节点的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11509700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTree: How to get the path of a selected node
提问by newSpringer
Is there a way to get the selected path of a selected node in a JTree like using something like
有没有办法像使用类似的东西一样在 JTree 中获取选定节点的选定路径
String pathForNode = JTree.getLastSelectedPathComponent().getPath().toString();
采纳答案by karrtojal
I used this:
我用过这个:
jTreeVarSelectedPath = "";
Object[] paths = jTreeDirectorios.getSelectionPath().getPath();
for (int i=0; i<paths.length; i++) {
jTreeVarSelectedPath += paths[i];
if (i+1 <paths.length ) {
jTreeVarSelectedPath += File.separator;
}
}
回答by Hitham S. AlQadheeb
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath();
if (tp != null) {
pathForNode = tp.getLastPathComponent();
}
}
});
http://www.coderanch.com/t/453540/GUI/java/Getting-path-file-selected-JTree
http://www.coderanch.com/t/453540/GUI/java/Getting-path-file-selected-JTree
Edit:
编辑:
Try
尝试
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if (tp != null) {
System.out.println(tp.toString());
}
}
回答by nilakantha singh deo
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath treepath = e.getPath();
System.out.println("Java: " + treepath.getLastPathComponent());
Object elements[] = treepath.getPath();
for (int i = 0, n = elements.length; i < n; i++) {
System.out.print("->" + elements[i]);
// JOptionPane.showMessageDialog(null,"->"+elements[i]);
//lblNewLabel.setText(">"+ elements[i]);
value+=elements[i]+"\";
}
//String x=String.valueOf(value);
//lblNewLabel.setText(String.valueOf(value));
JOptionPane.showMessageDialog(null, value);
//System.out.println(value);
}
});
static String value=""; //add this just before the void main function
In C# .net it used to be straightforward to get the path and bit intuitive for me .
在 C# .net 中,获取路径过去很简单,对我来说有点直观。