How to Restrict Jfilechooser to a Directory

How do I restrict JFileChooser to a directory?

You can probably do this by setting your own FileSystemView.

How to restrict a JFileChooser to a custom file type?

I actually have a program I am writing at the moment that has multiple JFileChooser's, each of them requiring to look for only specific file types. This example would allow you to have the same idea, so that if in the future, you need to allow for different file types, you are ready to go. I have created a custom class that extends upon FileFilter

public class CustomExtension extends FileFilter
{
private String type;

public CustomExtension(String type)
{
this.type = type;
}

public Boolean accept(File file)
{
if(file.isDirectory())
return true;

String ext = getExtension(file);
if(ext == null)
return false;

switch(type)
{
case "battle":
if(ext.equals("battle"))
return true;
else
break;
default:
System.out.println(type + " has not been set up in the switch statement yet");
}

return false;
}

public String getDescription()
{
switch(type)
{
case "battle":
return "Only battle file supported";
}
}

public String getExtension(File f)
{
String ext = null;
String filename = f.getName();

int i = filename.lastIndexOf('.');

if(i > 0 && i < filename.length() - 1)
ext = s.substring(i + 1).toLowerCase();

return ext;
}
}

I have been using this for a while now and I haven't noticed any bugs. To set up a JFileChooser so that it uses this filter, you would use:

JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new CustomExtension("battle"));

Now your JFileChooser will only display directories, and files that end in .battle

JFileChooser, want to lock it to one directory

Make a custom FileSystemView, use it as the argument to one of the JFileChooser constructors that accepts an FSV..

How to restrict file choosers in java to specific files?

For example, if you want to filter your JFileChooser to strictly display most commonly found image files, you would use something like this:

FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif", "jpeg");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);

The first argument is the description (what gets displayed upon selection at the bottom) and the second argument are the informal file extensions.

Is it possible to restrict the files available to a specific directory with a JFileChooser?

You can create a custom FileSytemView that allows you to only specify a single file root.

Check out Single Root File Chooser for an example of this approach.



Related Topics



Leave a reply



Submit