我想在JTree中只顯示目錄,但我的下面的代碼顯示的是目錄和文件都可以。任何人都可以幫助我只顯示目錄。如何僅顯示JTree中的目錄?
//Class1
public class FileBrowser implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
@Override
public void run() {
JFrame frame = new JFrame("File Browser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File fileRoot = new File("C:\\JDeveloper\\Testing");
root = new DefaultMutableTreeNode(new FileNodes(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
@Override
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean bSelected,
boolean bExpanded,
boolean bLeaf,
int iRow,
boolean bHasFocus) {
Component c = super.getTreeCellRendererComponent(tree, value,
bSelected, bExpanded, bLeaf, iRow, bHasFocus);
return c;
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setLocationByPlatform(true);
frame.setSize(640, 480);
frame.setVisible(true);
CreateChildNode ccn = new CreateChildNode(fileRoot, root);
new Thread(ccn).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new FileBrowser());
}
}
//Class 2
class CreateChildNode implements Runnable {
private DefaultMutableTreeNode root;
private File fileRoot;
public CreateChildNode(File fileRoot, DefaultMutableTreeNode root) {
this.fileRoot = fileRoot;
this.root = root;
}
@Override
public void run() {
createChildren(fileRoot, root);
}
private void createChildren(File fileRoot,
DefaultMutableTreeNode root) {
File[] files = fileRoot.listFiles();
for (File child : files) {
System.out.println("Path :" +child.getName());
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(new FileNodes(child));
System.out.println("Child Node :" +childNode);
System.out.println("File :" +child.getAbsoluteFile());
root.add(childNode);
if (child.isDirectory()) {
createChildren(child, childNode);
}
}
}
}
class FileNodes {
private File file;
public FileNodes(File file) {
this.file = file;
}
public File getFile() {
return file;
}
@Override
public String toString() {
String name = file.getName();
if (name.equals("")) {
return file.getAbsolutePath();
} else {
return name;
}
}
}
感謝您的解決方案,我已經嘗試了這兩種解決方案,但它僅以文件作爲葉節點顯示目錄。 – user6577633
它將僅包含文件的目錄顯示爲葉節點。請幫我解決這個問題,以便在JTree中只能看到文件夾,並且沒有文件。 – user6577633
@ user6577633我已更新代碼段以過濾出文件。 –