I have a JTree which contains file/directory, i want to get a list which contains current list of this JTree.
How can i do it?
menuItemZip.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
boolean exist=false;
File[] files = (File[]) tree.getModel().getRoot();
for (File file : files) {
if (file.getName().equals(selectedFile.getName()+".zip"))
exist = true;
break;
}
if(exist ==true)
new ZipWorkers(selectedFile,WORKING,status).execute();
btnRefresh.doClick();
}
});
Edited as new solution: just i don't know if it is a good solution?
menuItemZip.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Enumeration enumeration = ((TreeNode) tree.getModel().getRoot()).children();
String filename = selectedFile.getName()+".zip";
boolean exist=false;
while (enumeration.hasMoreElements()){
String file = ((File) enumeration.nextElement()).getName();
if(file.equals(filename)){
exist=true;
break;
}
}
if(exist ==true)
new ZipWorkers(selectedFile,WORKING,status).execute();
btnRefresh.doClick();
}
});
You will need to recursively descend into directories (see File.isDirectory()
to determine if it is). The recursiveness can be achieved by writing a function that iterates over an array of files and will call itself with the children of a directory
boolean doesExist(File[] files, String searchFileName) {
boolean exists = false;
for (File f : files) {
if (f.getName().equals(searchFileName)) {
exist = true;
} else if (f.isDirectory()) {
exist = doesExist(f.listFiles(), searchFileName);
}
if (exist) {
break; // no need to proceed further
}
}
return exist;
}
then call it with
doesExist((File[]) tree.getModel().getRoot(), selectedFile.getName()+".zip");