How to constrain JFileChooser to select particular number files?

雨燕双飞 提交于 2019-12-11 04:01:54

问题


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 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().

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!