我正在用Java创建文件浏览器,当我右键单击树中的节点(文件或文件夹名称)时,将弹出一个窗口,显示文件或文件夹信息。但是,当我使用鼠标右键单击时,只有应用程序只能识别根节点,而对于其他节点,它将显示null。而且我有一个walk()方法可以遍历每个文件和文件夹,它运行良好,所以我不认为是因为这种方法。
public class NewJFrame extends javax.swing.JFrame {
private DefaultTreeModel model;
private JPopupMenu menu;
public NewJFrame() {
initComponents();
menu = new JPopupMenu();
JMenuItem cut = new JMenuItem("Rename");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
jTree1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
menu.show(e.getComponent(), e.getX(), e.getY());
int selRow = jTree1.getRowForLocation(e.getX(), e.getY());
TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());
jTree1.setSelectionPath(selPath);
if (selRow > -1) {
jTree1.setSelectionRow(selRow);
}
System.out.println(jTree1.getClosestPathForLocation(
e.getX(), e.getY()));
System.out.println("Path: " + selPath);
} else {
menu.setVisible(false);
}
}
});
DefaultMutableTreeNode root = new DefaultMutableTreeNode("File
System");
model = new DefaultTreeModel(root);
jTree1.setModel(model);
jTree1 = new JTree(root);
DefaultMutableTreeNode d = new DefaultMutableTreeNode("D:");
root.add(d);
walk("D:\\", d);
jTree1.updateUI();
}
public void walk(String path, DefaultMutableTreeNode top) {
File root = new File(path);
File[] list = root.listFiles();
if (list != null) {
for (File f : list) {
if (f.isDirectory()) {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(f.getName());
top.add(node);
walk(f.getAbsolutePath(), node);
} else {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(f.getName());
top.add(node);
}
}
}
}
}