如何限制JFileChooser选择特定的数字文件? [英] How to constrain JFileChooser to select particular number files?

查看:68
本文介绍了如何限制JFileChooser选择特定的数字文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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 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.

这篇关于如何限制JFileChooser选择特定的数字文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆