如何限制JFileChooser选择特定的数字文件? [英] How to constrain JFileChooser to select particular number files?
问题描述
使用JFileChooser
,我已通过setMultiSelectionEnabled(true)
启用了多选模式,但是如何设置限制以使用户只能选择特定数量的文本(或其他)文件?
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;
}
可能有几种方法:
-
创建自定义
FileChooserUI
的子类,并在实现嵌套类SelectionListener
的过程中限制选择. -
创建自定义文件浏览器,如此处所示,并在相关的侦听器中限制选择. /p>
-
使用现有的
FileChooser
并在选择超过三个时显示一个对话框;请考虑使用包含JTable
的复选框,如此处所示. -
使用单独的选择器面板,如此处所示,用于通过
createPathPanel()
的两个文件.
最佳选择和确切的细节将取决于用例.
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;
}
Several approaches are possible:
Create a custom
FileChooserUI
by subclassingBasicFileChooserUI
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.
这篇关于如何限制JFileChooser选择特定的数字文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!