2

Using JFileChooser, I have enabled multi-selection mode by setMultiSelectionEnabled(true), but how can I set a limit so that the user can only select a particular number of text (or other) files?

public File[] fileSelect() {
    fileChooser = new JFileChooser();
    fileNameExtFilter = new FileNameExtensionFilter("Text File","txt");
    fileChooser.setCurrentDirectory(new java.io.File("."));
    fileChooser.setDialogTitle("Open Question Set");
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setFileFilter(fileNameExtFilter);
    fileChooser.setMultiSelectionEnabled(true);

    if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        return fileChooser.getSelectedFiles();
    else
        return null;
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Kamal Vidhani
  • 133
  • 1
  • 2
  • 12
  • 1
    *"..but how to put limit on that so that user can only pick three files."* Why only 3? If that were the case, I'd offer the user a single selection file chooser, 3 times. – Andrew Thompson Sep 11 '15 at 13:08
  • I have to send path of those files to other class's constructor so can't do looping I guess.And "only 3" is in my case.I agree with you, I should ask in general. – Kamal Vidhani Sep 11 '15 at 13:47

1 Answers1

4

Several approaches are possible:

  • Create a custom FileChooserUI by subclassing BasicFileChooserUI and limit the selection in your implementation of the nested class SelectionListener.

  • Create a custom file browser, as shown here, and limit the selection in the relevant listener.

  • Use the existing FileChooser and present a dialog when the selection exceeds three; consider using a JTable containing checkboxes as shown here.

  • Use separate chooser panels, as shown here for two files via createPathPanel().

image

The best choice and exact details will depend on the use case.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045