有没有办法像使用类似的东西来获取 JTree 中选定节点的选定路径
String pathForNode = JTree.getLastSelectedPathComponent().getPath().toString();
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
编辑:
尝试
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());
}
}
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
在 C# .net 中,它曾经很容易获得路径并且对我来说有点直观。
我用这个:
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;
}
}