Reputation: 1926
Below is my code to open a JFileChooser
on the click of a button. I have created a filter to allow the selection of only .jpg files, but my code doesn't work as expected. All types of files are shown in JFileChooser
diaog box. Part of code:
MyFileFilter filter;
fPhoto=new JFileChooser();
fPhoto.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fPhoto.setFileFilter(filter);
MyFileFilter class:
public class MyFileFilter extends javax.swing.filechooser.FileFilter{
public boolean accept(File f){
return f.isDirectory()||(f.isFile()&&f.getName().toLowerCase().endsWith(".jpg"));
}
public String getDescription(){
return ".jpg files";
}
}
Upvotes: 1
Views: 1306
Reputation: 20741
If you want browse specified files, Take a look at this code
try
{
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.isDirectory()||file.getName().endsWith(".JPG")||file.getName().endsWith(".jpg"));
}
@Override
public String getDescription() {
return "Multi-Video Files";
}
});
File file;
if(JFileChooser.APPROVE_OPTION==fc.showDialog(null, "Select Files"))
{
File file = fc.getSelectedFile(); //HERE YOU WILL GET THE SELECTED FILE
}
}catch(Exception e){System.out.println("error");
}
If you want to browse only directories then
JFileChooser fc = new JFileChooser();
File file;
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(JFileChooser.APPROVE_OPTION==fc.showDialog(null, "Select"))
{
File file = fc.getSelectedFile(); //HERE YOU WILL GET THE SELECTED DIRECTORY PATH
}
Upvotes: 3
Reputation: 159754
You need to instantiate your filter
. Having a null
FileFilter
will result in no file types being filtered out:
MyFileFilter filter = new MyFileFilter();
Upvotes: 5