Java - 非常基本的JFileChooser问题

时间:2014-07-13 01:07:32

标签: java jfilechooser

我想创建一个JFileChooser,让用户选择包含单词“hello”的任何文件或目录。也就是说,以下是有效的选择:

C:\hello\
C:\fun\hello.txt
etc.

我怎样才能使这个工作?我试过了:

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

        JFileChooser f = new JFileChooser();
        f.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        f.setFileFilter(new FileFilter() {

            public boolean accept(File file) {
                return file.getAbsolutePath().contains("hello");
            }

            public String getDescription() {
                return "hi";
            }

        });
        f.showOpenDialog(this);

但我的JFileChooser是空白的。也就是说,我在C:\中看不到文件夹“有趣”。

enter image description here

1 个答案:

答案 0 :(得分:1)

我不得不做一些额外的覆盖。

两个自定义类和一个跑步者类。试一试。

package custom_file_chooser;

import java.io.File;

import javax.swing.filechooser.FileFilter;

public class MyFileFilter extends FileFilter {

    private String filterString;

    public MyFileFilter(String filterString) {
        super();
        this.filterString = filterString;
    }

    @Override
    public boolean accept(File file) {
         return  file.isDirectory() || file.getName().toLowerCase().contains(filterString);
     }

     @Override
     public String getDescription() {
         return filterString + " only";
     }    
}


package custom_file_chooser;

import java.io.File;

import javax.swing.JFileChooser;

public class MyFileChooser extends JFileChooser {

    private String filterString;

    public MyFileChooser(String filterString) {
        super();
        this.filterString = filterString;

        setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        setFileFilter(new MyFileFilter(filterString));
    }

    @Override
    public void approveSelection() {
        File file = this.getSelectedFile();
        if (!file.isDirectory() || file.getName().contains(filterString)) {
            super.approveSelection();           
        }   
    }
}


package custom_file_chooser;

import java.io.File;

import javax.swing.JFileChooser;

public class CustomFileChooserRunner {


    public static void main(String[] args) {

        MyFileChooser f = new MyFileChooser("hello");
        int result;

        result = f.showOpenDialog(null);

        if (result == JFileChooser.APPROVE_OPTION) {
            File file = f.getSelectedFile();
            System.out.println("You chose to open: " +
                    file.getName() + (file.isDirectory() ? " directory" : " file"));
        }
    }
}