簡體   English   中英

允許JFileChooser僅選擇特定的文件名格式

[英]Allow JFileChooser to select only specific filename format

JFileChooser中是否可以使用帶通配符的FileFilter?

當文件瀏覽器打開時,我希望用戶在所有* .def文件中選擇一個特定文件,例如* _SomeFixedFormat.def文件。

使用FileNameExtensionFilter,我可以對.def文件執行此操作,但不能對此特定文件執行此操作。

FileNameExtensionFilter fileFilter=new FileNameExtensionFilter(".def", "def");
fileChooser.setFileFilter(fileFilter);

創建自己的FileFilter

JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter(){
    @Override
    public boolean accept(File file){
        // always accept directorys
        if(file.isDirectory())
            return true;
        // but only files with specific name _SomeFixedFormat.def
        return file.getName().equals("_SomeFixedFormat.def");
    }
    @Override
    public String getDescription() {
        return ".def";
    }
});

更改FileNameExtensionFilter(".def", def); FileNameExtensionFilter(".def", "_yourFixedFormat.def"); 我不確定這是否有效。 如果不是,則僅將其限制為.def,然后在選擇文件時,檢查文件名是否等於您的格式,否則,請再次打開JFileChooser。

用法

DefFileFilter fileFilter=new DefFileFilter (new String[] {"DEfFile1"});
fileChooser.setFileFilter(fileFilter);

過濾

package ui.filechooser.filter;

import java.io.File;
import javax.swing.filechooser.FileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Igor
 */
public class DefFileFilter extends FileFilter {

    public final static String DEF_EXT = "def";
    //def file name  example : "DEfFile1", "DefFile2" ....
    private String[] allowedNames;

    public DefFileFilter() {
        this(null);
    }

    public DefFileFilter(String names[]) {
        this.allowedNames = name;
    }

    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }

        String extension = getExtension(f);
        if (extension != null) {
            if (extension.equals(DEF_EXT)) {
                if(allowedNames != null && !StringUtils.indexOfAny(getBaseName(f.getName), allowedNames)) {
                    return false;
                } else {
                 return true;
                }

            } else {
                return false;
            }
        }

        return false;
    }

    public static String getBaseName(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index == -1) {
            return fileName;
        } else {
            return fileName.substring(0, index);
        }
    }

     public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 && i < s.length() - 1) {
            ext = s.substring(i + 1).toLowerCase();
        }
        return ext;
    }

    public String getDescription() {
        return "Excel file";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM