JFileChooser, want to lock it to one directory

僤鯓⒐⒋嵵緔 提交于 2019-11-29 11:58:44

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

Set a FileView and override the isTraversable method so that it returns true only for the directory you want the user to see.

Here is an example:

String getProperty = System.getProperty("user.home");
final File dirToLock = new File(getProperty + "/Dropbox/Prosjekt RMI/SERVER/");
JFileChooser fc = new JFileChooser(dirToLock);
fc.setFileView(new FileView() {
    @Override
    public Boolean isTraversable(File f) {
         return dirToLock.equals(f);
    }
});

In my case I needed to disable both directory navigation and choosing a different file extension Here's another approach for posterity: a small recursive method to disable the navigation controls:

private void disableNav(Container c) {
for (Component x : c.getComponents())
  if (x instanceof JComboBox)
    ((JComboBox)x).setEnabled(false);
  else if (x instanceof JButton) {
    String text = ((JButton)x).getText();
    if (text == null || text.isEmpty())
      ((JButton)x).setEnabled(false);
    }
  else if (x instanceof Container)
    disableNav((Container)x);
  }

Then call as follows:

JFileChooser fc = new JFileChooser(imgDir);
disableNav(fc);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif", "png");
fc.setFileFilter(filter);
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!