Using a FileDialog to choose a file of a certain extension
-
12-09-2019 - |
Question
I am trying to use a FileDialog file chooser because I really need java app to have the native apple file chooser (I know we all hate hate the lack of portability but this is what I need). I am trying to make my file chooser allow the user to pick files that end with .ws. Here is what I tried:
FileDialog fd = new
FileDialog(_sharedInstance,rsc.str("480"),FileDialog.LOAD);
// fd.setFile("*.ws");
class WSFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".ws"));
}
};
FilenameFilter wsFilter = new WSFilter();
fd.setFilenameFilter(wsFilter);
fd.setDirectory(_projectsBaseDir.getPath());
fd.setLocation(50,50);
// fd.setFile("*");
fd.setVisible(true);
For some reason my file chooser won't allow me to pick any files. Any ideas?
Solution
Answer was I need this call: System.setProperty("apple.awt.fileDialogForDirectories", "false");
OTHER TIPS
Why not use JFileChooser?
JFileChooser fileChooser = new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
String filename = file.getName();
return filename.endsWith(".java");
}
public String getDescription() {
return "*.java";
}
}
Haven't this been asked before?
Anyway, you may try to change L&F and keep using JFileChooser.
I've heard this one is good:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow