Starting a JFileChooser at a specified directory and only showing files of a specific type

元气小坏坏 提交于 2019-12-02 10:24:50

You need to construct your JFileChooser with the directory you want to start in and then pass a FileFilter into it before setting visible.

    final JFileChooser fileChooser = new JFileChooser(new File("File to start in"));
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            final String name = f.getName();
            return name.endsWith(".png") || name.endsWith(".jpg");
        }

        @Override
        public String getDescription() {
            return "*.png,*.jpg";
        }
    });
    fileChooser.showOpenDialog(GridCreator.this);

This example filters for files ending in ".png" or ".jpg".

Read the API: http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html

At the very top of the javadoc page is an example of nearly exactly what you want to do:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

The class that you are looking for in general is FileFilter, which is abstract. See the javadoc: http://docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileFilter.html

Putting it all into a concise form, here is a flexible file chooser routine. It specifies initial directory and file type and it furnishes the result both as a file or a complete path name. You may also want to set your entire program into native interface mode by placing the setLookAndFeel command at the Main entry point to your program.

String[] fileChooser(Component parent, String dir, String typeFile) {
    File dirFile = new File(dir);
    JFileChooser chooser = new JFileChooser();
    // e.g. typeFile = "txt", "jpg", etc.
    FileNameExtensionFilter filter = 
        new FileNameExtensionFilter("Choose a "+typeFile+" file",
            typeFile); 
    chooser.setFileFilter(filter);
    chooser.setCurrentDirectory(dirFile);
    int returnVal = chooser.showOpenDialog(parent);

    String[] selectedDirFile = new String[2];
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        // full path
        selectedDirFile[0] = chooser.getSelectedFile().getPath();
        // just filename
        selectedDirFile[1] = chooser.getSelectedFile().getName();
    }

    return selectedDirFile;
 }

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