JFileChooser, want to lock it to one directory

后端 未结 3 1261
半阙折子戏
半阙折子戏 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: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);
    ...
    

提交回复
热议问题