FileChooser handling directories in the fileName field
Brought to you by:
zander
|
From: Matthew B. <mat...@la...> - 2008-02-08 21:08:21
|
I found your project today and started working with it. FileChooser to
be a great improvement over JFileChooser. I found that typing
directories (especially absolute paths) into the file area did not work
well. Even though there is a directory combo box, I think users are
used to being able to navigate from here.
I made these changes for my own use. Please feel free to use if you
find them useful.
private void acceptFileSlot() {
File f = getSelectedFile();
if (f != null ) {
if (f.isDirectory()) {
directory.setSelectedItem(f);
+ fileName.setSelectedItem(""); // clear typed
directory from fileName after accepting
}
else {
// store selected files...
storeLastVisitedFiles(f);
// notify listeners a File has been selected..
firePropertyChange(FILE_ACCEPTED, null, f);
}
}
}
public File[] getSelectedFiles() {
Object selectedItem = fileName.getSelectedItem();
if (selectedItem == null || selectedItem.equals("")) return new
File[0];
// it might be a file selected from history...
// this cannot be a string since otherwise "the current
directory" will be added to..
if (selectedItem instanceof File) return new
File[]{(File)selectedItem};
String selectedString = ((String)selectedItem).trim();
if (selectedString.charAt(0) != '\"')
{
+ File f = getFile((File)directory.getSelectedItem(),
selectedString);
+ return f == null ? new File[0] : new File[] {f};
}
ArrayList fileNames = new ArrayList();
File dir = (File)directory.getSelectedItem();
int indexOfQuote = -1;
while ( (indexOfQuote = selectedString.indexOf('\"',
indexOfQuote +1)) != -1) {
int endIndexOfQuote = selectedString.indexOf('\"',
indexOfQuote +1);
+ File f = getFile(dir,
selectedString.substring(indexOfQuote+1, endIndexOfQuote));
+ if (null != f)
+ fileNames.add(f);
indexOfQuote = endIndexOfQuote;
if (indexOfQuote < 0) break;
}
return (File[]) fileNames.toArray(new File[0]);
}
+ static boolean fileMustExist = true;
+
+ protected static File getFile(File dir, String path)
+ {
+ File f = new File(path);
+ if (!(f.isAbsolute() || path.startsWith("/") ||
path.startsWith(File.separator)))
+ f = new File(dir,path);
+ f = getFile(f);
+ if (fileMustExist && !f.exists())
+ return null;
+ // remove .. if any from path
+ try { f = f.getCanonicalFile(); } catch (IOException x) {}
+ return f;
+ }
|