问题
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;
}
回答1:
Several approaches are possible:
Create a custom FileChooserUI by subclassing
BasicFileChooserUI
and limit the selection in your implementation of the nested classSelectionListener
.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 aJTable
containing checkboxes as shown here.Use separate chooser panels, as shown here for two files via
createPathPanel()
.

The best choice and exact details will depend on the use case.
来源:https://stackoverflow.com/questions/32523630/how-to-constrain-jfilechooser-to-select-particular-number-files