How to make JFileChooser Display only a Folder that has some specific name Java

一世执手 提交于 2019-12-01 11:42:48

问题


Is there any way that when the JFileChooser loads, it only display folder having name "Hello" only.

Here is my code: It displays all folders and also file having extension .py and .java. I want to add that folder name restriction to it.

FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Select Source Code To Analyze", "java","py");
            jfc.setFileFilter(filter);
            //jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    JButton btnNewButton = new JButton("Select Erroneous File"); //SELECT File Button.
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             if (jfc.showOpenDialog(contentPane) !=
                        JFileChooser.APPROVE_OPTION)
                            return;
                    File f = jfc.getSelectedFile();

Current Program Output:

I want the output to be somewhat like this:Only Display Folder Having name "Hello" and rest of files only.


回答1:


Use File filter like this.

javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
jfc.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
jfc.setFileFilter(new javax.swing.filechooser.FileFilter(){
    @Override
    public boolean accept(java.io.File file){
        //return (file.isDirectory() && file.getName().equals("Hello")) || !file.isDirectory(); 
        // Get only hello folder and .py files
        //return (file.isDirectory() && file.getName().equals("Hello")) || (!file.isDirectory() && file.getName().toLowerCase().endsWith(".py"));
        // Get only hello folder and .java files if Hello folder is opened else .py files
        return (file.isDirectory() && file.getName().equals("Hello")) || 
        (!file.isDirectory() && file.getParentFile().getName().equals("Hello") && 
        file.getName().toLowerCase().endsWith(".java")) || 
        (!file.isDirectory() && file.getName().toLowerCase().endsWith(".py"));
    }
    @Override
    public String getDescription() {
        return "Hello Folder and Other Files";
    }
});


来源:https://stackoverflow.com/questions/15330285/how-to-make-jfilechooser-display-only-a-folder-that-has-some-specific-name-java

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