0

我正在寻找一种让 JFileChooser 允许用户从仅包含在 Eclipse 项目的 bin 文件中的 txt 文件中进行选择的方法。有没有办法让 JFileChooser 弹出并显示位于 bin 文件夹中的选定数量的 txt 文件?

4

3 回答 3

3

您可以参考以下代码,只需指定文件夹/目录的绝对或相对路径

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "TXT files", "txt");
chooser.setFileFilter(filter);
chooser.setCurrentDirectory("<YOUR DIR COMES HERE>");
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

JFileChooser

于 2012-12-06T12:29:16.490 回答
2

另一种方法是实现 FileSystemView 以便它只显示您的目录并防止在层次结构或其他“驱动器”中上升。

这是这样一个 FileSystemView 的演示。您必须在输入中提供根目录(即 bin 的路径,可能是诸如new File("bin")工作目录被认为是 Eclipse 项目的根目录,这是 Eclipse 默认执行的操作)。

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;

public class TestJFileChooser2 {

    public static class MyFileSystemView extends FileSystemView {

        private File root;

        public MyFileSystemView(File root) {
            super();
            try {
                this.root = root.getCanonicalFile();
            } catch (IOException e) {
                this.root = root;
            }
        }

        @Override
        public File[] getRoots() {
            return new File[] { root };
        }

        @Override
        public File createNewFolder(File containingDir) throws IOException {
            return FileSystemView.getFileSystemView().createNewFolder(containingDir);
        }

        @Override
        public File createFileObject(String path) {
            File file = super.createFileObject(path);
            if (isEmbedded(file)) {
                return file;
            } else {
                return root;
            }
        }

        @Override
        public File createFileObject(File dir, String filename) {
            if (isEmbedded(dir)) {
                return super.createFileObject(dir, filename);
            } else {
                return root;
            }

        }

        @Override
        public File getDefaultDirectory() {
            return root;
        }

        private boolean isEmbedded(File file) {
            while (file != null && !file.equals(root)) {
                file = file.getParentFile();
            }
            return file != null;
        }

        @Override
        public File getParentDirectory(File dir) {
            File parent = dir.getParentFile();
            if (isEmbedded(parent)) {
                return parent;
            } else {
                return root;
            }
        }
    }

    protected void initUI() {
        JFrame frame = new JFrame("Test file chooser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JButton ok = new JButton("Click me to select file");
        ok.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final JFileChooser openFC = new JFileChooser(new MyFileSystemView(new File("")));
                        openFC.setDialogType(JFileChooser.OPEN_DIALOG);
                        // Configure some more here
                        openFC.showDialog(ok, null);
                    }
                });
            }
        });
        frame.add(ok);
        frame.setBounds(100, 100, 300, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                new TestJFileChooser2().initUI();
            }
        });
    }
}
于 2012-12-06T16:16:47.447 回答
2

所以你只想显示目录中的某些文本文件?

如果找到匹配项,则使用FileFilter将检查文件名与ArrayList文件名的匹配项,它将返回true允许JFileChooser显示文件

就像是:

JFileChooser fc=..;
fc.setCurrentDirectory(new File("path/to/bin/"));//put path to bin here

 ....     

 ArrayList<String> filesToSee=new ArrayList<>();
 //add names of files we want to be visible to user of JFileChooser
 filesToSee.add("file1.txt");
 filesToSee.add("file2.txt");

fc.addChoosableFileFilter(new MyFileFilter(filesToSee));

//By default, the list of user-choosable filters includes the Accept All filter, which        enables the user to see all non-hidden files. This example uses the following code to disable the Accept All filter:
fc.setAcceptAllFileFilterUsed(false);

....

class MyFileFilter extends FileFilter {

     private ArrayList<String> files;

     public MyFileFilter(ArrayList<String> files) {
         this.files=files;
     }

    //Accept only files in passed array
    public boolean accept(File f) {

        for(String s:files) {
            if(f.getName().equals(s)) {
                return true;
             }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Specific Files";
    }
}

参考:

于 2012-12-06T13:13:58.470 回答