JFileChooser, want to lock it to one directory

后端 未结 3 1253
半阙折子戏
半阙折子戏 2020-12-11 09:17

I have this program where u can download files and i want the JFileChooser to be locked to one folder(directory) so that the user cant browse anything else. He can only choo

相关标签:
3条回答
  • 2020-12-11 09:47

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

    0 讨论(0)
  • 2020-12-11 09:50

    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);
    ...
    
    0 讨论(0)
  • 2020-12-11 09:55

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题